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;
}