Input
The program input is from the std input. Each data set in the input contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.Output
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 mnpSample Output
4 2 0 状态转移方程
f(i,j)={f(i−1,j−1)+1max(f(i−1,j),f(i,j−1)),,a[i]=b[j]a[i]≠b[j] #include <iostream> #include <cstdio> #include <algorithm> #include <string> #include <cstring> #include <vector> using namespace std; int dp[1000][1000]; int main(){ #ifdef TEST freopen("test.txt", "r", stdin); #endif // TEST string str1, str2; int len1, len2; while(cin >> str1 >> str2){ len1 = str1.length(), len2 = str2.length(); memset(dp, 0, sizeof(dp)); for(int i = 0; i < len1; i++){ for(int j = 0; j < len2; j++){ if(str1[i] == str2[j]) dp[i+1][j+1] = dp[i][j] + 1; else dp[i+1][j+1] = max(dp[i][j+1],dp[i+1][j]); } } cout << dp[len1][len2] << endl; } return 0; }