1458:Common Subsequence(动态规划)

 

总时间限制: 
1000ms
 
内存限制: 
65536kB
描述
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.
输入
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.
样例输入
abcfbc         abfcab
programming    contest 
abcd           mnp
样例输出
4
2
0
来源
Southeastern Europe 2003

 

 

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 char s1[1000],s2[1000];
 4 int len1,len2;
 5 int ml[1000][1000];
 6 
 7 int main() {
 8 
 9     while(scanf("%s%s",s1+1,s2+1)>0) {//从s1[1]开始写入数据 
10         len1=strlen(s1+1);
11         len2=strlen(s2+1);
12         for(int i=0;i<=len1;i++){
13             ml[i][0]=0;
14         }
15         for(int i=0;i<=len2;i++){
16             ml[0][i]=0;
17         }
18         for(int i=1;i<=len1;i++){
19             for(int j=1;j<=len2;j++){
20                 if(s1[i]==s2[j]){
21                     ml[i][j]=ml[i-1][j-1]+1;
22                 }
23                 else ml[i][j]=max(ml[i-1][j],ml[i][j-1]);
24             }
25         }
26         cout<<ml[len1][len2]<<endl;
27     }
28 
29     return 0;
30 }

 

#include <bits/stdc++.h>using namespace std;char s1[1000],s2[1000];int len1,len2;int ml[1000][1000];
int main() {
while(scanf("%s%s",s1+1,s2+1)>0) {//从s1[1]开始写入数据 len1=strlen(s1+1);len2=strlen(s2+1);for(int i=0;i<=len1;i++){ml[i][0]=0;}for(int i=0;i<=len2;i++){ml[0][i]=0;}for(int i=1;i<=len1;i++){for(int j=1;j<=len2;j++){if(s1[i]==s2[j]){ml[i][j]=ml[i-1][j-1]+1;}else ml[i][j]=max(ml[i-1][j],ml[i][j-1]);}}cout<<ml[len1][len2]<<endl;}
return 0;}

posted @ 2020-03-29 14:52  瓜瓜爱呱呱  阅读(186)  评论(0编辑  收藏  举报