Common Subsequence
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 12 Accepted Submission(s) : 6
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
The program input is from a text file. Each data set in the file 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.
Sample Input
abcfbc abfcab programming contest abcd mnp
Sample Output
4 2 0
Source
经典dp:
#include<iostream>
#include<cstring>
using namespace std;
char s1[2013];
char s2[2013];
int dp[2013][2013];
int main()
{
while(scanf("%s%s",s1,s2)!=EOF)
{
int a=strlen(s1);
int b=strlen(s2);
for(int i=0;i<a;i++)
{
dp[i][0]=0;
}
for(int i=0;i<b;i++)
{
dp[0][i]=0;
}
for(int i=1;i<a+1;i++)
for(int j=1;j<b+1;j++)
{
if(s1[i-1]==s2[j-1])
{
dp[i][j]=dp[i-1][j-1]+1;
}
else{
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
cout<<dp[a][b]<<endl;
}
return 0;
}