POJ - 1458 Common Subsequence

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.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

即为求最小编辑距离,用动态规划即可。
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cmath>
 5 
 6 using namespace std;
 7 
 8 string s1,s2;
 9 int f[500][500];
10 
11 int main()
12 {
13     while(cin>>s1>>s2)
14     {
15         memset(f,0,sizeof(f));
16         int a,b;
17         a=s1.size();
18         b=s2.size();
19         //cout<<a<<" "<<b<<endl;
20         //f[0][1]=f[1][0]=0;
21         for(int i=0;i<a;i++)
22             for(int j=0;j<b;j++)
23             {
24                 if(s1[i]==s2[j])
25                     f[i+1][j+1]=f[i][j]+1;
26                     else
27                         f[i+1][j+1]=max(f[i][j+1],f[i+1][j]);
28             }
29         cout<<f[a][b]<<endl;
30     }
31     
32     
33     return 0;
34 }

 

posted @ 2017-08-03 16:05  西北会法语  阅读(85)  评论(0编辑  收藏  举报