joj1968: Common Subsequence

 1968: Common Subsequence


ResultTIME LimitMEMORY LimitRun TimesAC TimesJUDGE
1s 4096K 781 227 Standard

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.

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           mnp

 

Sample Output

 

4
2
0

 

 


Submit / Problem List / Status / Discuss

 经典的DP,最大公共子序列。
 
 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 int dp[500][500];
 5 char c1[500], c2[500];
 6 
 7 int main()
 8 {
 9     //freopen("in.txt", "r", stdin);
10 
11     while (scanf("%s%s", c1, c2) == 2)
12     {
13         int len1, len2, i, j;
14         len1 = strlen(c1);
15         len2 = strlen(c2);
16 
17         for (i = 0; i <= len1; ++i)
18         {
19             dp[0][i] = 0;
20         }
21         for (j = 0; j <= len2; ++j)
22         {
23             dp[j][0] = 0;
24         }
25 
26         for(i = 1; i <= len1; i++)
27         {
28             for(j = 1; j <= len2; j++)
29             {
30                 if(c1[i-1] == c2[j-1])
31                 {
32                     dp[i][j] = dp[i-1][j-1] + 1;
33                 }
34                 else
35                 {
36                     if(dp[i-1][j] > dp[i][j-1])
37                     {
38                         dp[i][j] = dp[i-1][j];
39                     }
40                     else
41                     {
42                         dp[i][j] = dp[i][j-1];
43                     }
44                 }
45             }
46         }
47         
48         printf("%d\n", dp[len1][len2]);
49     }
50     
51     return 0;
52 }

 

posted @ 2012-05-08 10:35  漂木  阅读(186)  评论(0编辑  收藏  举报