Problem Description
给定两个序列X=
Input
输入数据有多组,每组有两行 ,每行为一个长度不超过500的字符串(输入全是大写英文字母(A,Z)),表示序列X和Y。
Output
每组输出一行,表示所求得的最长公共子序列的长度,若不存在公共子序列,则输出0。
Example Input
ABCBDAB
BDCABA
Example Output
4
代码
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int main( )
{
char s1[501],s2[501];
while(cin>>s1>>s2)
{
int len1=strlen(s1);
int len2=strlen(s2);
int dp[502][502],ans=0;
/*
设dp[i][j]表示:
s1的左边i个字符形成的子串,与s2:左边的j个字符形成
的子串的最长公共子序列的长度(i,j从0开始算)
dp[i][j]就是本题的状态
*/
memset(dp,0,sizeof(dp));
for(int i=1;i<=len1;++i)
{
for(int j=1;j<=len2;++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]);
//ans=max(ans,dp[i][j]);
}
}
cout<<dp[len1][len2]<<endl;
}
return 0;
}