Description
读入两个字符串, 求两个字符串能构成的最长公共子序列的长度
找到一个子序列, 既是A的也是B的, 要求子序列的长度最大
读入遇到 ‘.’ 结束
字符串的长度不超过5000
Input
读入两个字符串
Output
打印一个整数
Sample Input Copy
ABCBDAB.
BACBBD.
Sample Output Copy
4
HINT
BCBD
#include<bits/stdc++.h>
using namespace std;
#define ios ios::sync_with_stdio(false); cin.tie(NULL);
//const int N = 510;
char a[5010];
char b[5010];
char c;
int len1,len2,len;
int dp[5010][5010];
int main()
{
for(int i=0; ; i++)
{
cin>>c;
if(c=='.')
break;
a[i] = c;
len1++;
}
for(int i=0; ; i++)
{
cin>>c;
if(c=='.')
break;
b[i] = c;
len2++;
}
for(int i=1; i<=len1; i++)
{
for(int j=1; j<=len2; j++)
{
if(a[i-1]==b[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[len1][len2]<<endl;
return 0;
}
思路理解
实际上dp列出了一个表格,当xi和yi相等时dp++,然后取最大值。