HDOJ-1159 Common Subsequence(动态规划,最长公共子列)

版权声明:个人学习笔记记录 https://blog.csdn.net/Ratina/article/details/84991465

链接:HDOJ-1159

Problem Description

A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = <x1, x2, …, xm> another sequence Z = <z1, z2, …, zk> is a subsequence of X if there exists a strictly increasing sequence <i1, i2, …, ik> of indices of X such that for all j = 1,2,…,k, xij = zj. For example, Z = <a, b, f, c> is a subsequence of X = <a, b, c, f, b, c> with index sequence <1, 2, 4, 6>. Given two sequences X and Y the problem is to find the length of the maximum-length common subsequence of X and Y.
The program input is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct. For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line.

Sample Input

abcfbc abfcab
programming contest
abcd mnp

Sample Output

4
2
0


题目大意:求两个字符串的最长公共子序列的长度


求最长公共子列属于动态规划基础题型,是在看了这位→→点击这里←←的讲解后明白的,写的十分详细。


dp[i][j],i 表示字符串a前 i 个字符,j 表示字符串b前 j 个字符,那么可以得出状态转移方程:
d p [ i ] [ j ] = { d p [ i 1 ] [ j 1 ] + 1 , a [ i ] = b [ j ] m a x ( d p [ i 1 ] [ j ] , d p [ i ] [ j 1 ] ) , a [ i ] b [ j ] dp[i][j]=\begin{cases} dp[i-1][j-1]+1, &amp;a[i]=b[j]\\ max(dp[i-1][j],dp[i][j-1]), &amp;a[i] \neq b[j] \end{cases}

其实用到了一些逆推的思维,从序列末尾往前推导,
当a、b字符串的最后一个字符相等,即a[i] == b[j],那么dp[i][j] = dp[i-1][j-1] + 1;
a[i]!=b[j],可以选择抛弃a最后一个或者b最后一个,因为公共子序列要最大长度,所以要在这两个情况择优。

此外,要考虑 i-1 或 j-1 越界的情况,可以在dp越界的地方围一圈0,或者处理时加特判。


以下代码:

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
	string a,b;
	while(cin>>a>>b)
	{
		int La=a.length(),Lb=b.length();
		int i,j;
		vector<vector<int> > dp(La,vector<int>(Lb));
		for(i=0;i<La;i++)
		{
			for(j=0;j<Lb;j++)   
			{                          //用三目运算符给 i==0 或 j==0 加个特判
				if(a[i]==b[j])
					dp[i][j]=(i==0||j==0)?1:dp[i-1][j-1]+1;
				else
					dp[i][j]=max(i==0?0:dp[i-1][j],j==0?0:dp[i][j-1]);
			}
		}
		cout<<dp[La-1][Lb-1]<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Ratina/article/details/84991465