Common Subsequence(最长公共字串-动态规划)
Common Subsequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 27834 Accepted Submission(s): 12392
Problem Description
A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X =
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
Southeastern Europe 2003
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
const int N=1010;
using namespace std;
int dp[N][N];
int main()
{
string s1,s2;
int stl1,stl2,i,j;
while(cin>>s1>>s2)
{
memset(dp,0,sizeof(dp));
stl1=s1.size();
stl2=s2.size();
for(i=1;i<=stl1;i++)
{
for(j=1;j<=stl2;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[stl1][stl2]<<endl;
}
}
还没有评论,来说两句吧...