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.
求最长公共子序列(不要求连续)
很经典的DP,在此贴两张图,相信必有秒懂的功效...
AC代码:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
typedef long long LL;
#define max(a,b) (a>b?a:b)
int dp[1000][1000];
int main()
{
string a,b;
while(cin>>a>>b)
{
int len_a,len_b;
len_a=a.length();
len_b=b.length();
//init
for(int i=0;i<=len_a;++i) dp[i][0]=0;
for(int j=0;j<=len_b;++j) dp[0][j]=0;
for(int i=1;i<=len_a;++i)
for(int j=1;j<=len_b;++j)
{
if(a[i-1]==b[j-1]) dp[i][j]=dp[i-1][j-1]+1;
else dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
cout<<dp[len_a][len_b]<<endl;
}
return 0;
}