Common Subsequence (POJ-1458HDU - 1159)

题面

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, x ij = 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 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.

输出

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.

样例输入

1abcfbc         abfcab
2programming    contest
3abcd           mnp

样例输出

14
22
30

提示

思路

代码

 1using namespace std;
 2typedef long long ll;
 3const int inf = 0x3f3f3f3f;
 4const int N = 1e3+5;
 5
 6char a[N], b[N];
 7int dp[N][N];
 8
 9int main(void) {
10    while(scanf("%s%s", a, b)==2) {
11        int la = strlen(a);
12        int lb = strlen(b);
13        for(int i=1; i<=la; i++) {
14            for(int j=1; j<=lb; j++) {
15                if(a[i-1]==b[j-1])
16                    dp[i][j] = dp[i-1][j-1]+1;
17                else
18                    dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
19            }
20        }
21        printf("%d\n", dp[la][lb]);
22    }
23    return 0;
24}