Problem Description
给定两个序列 X={x1,x2,…,xm} 和 Y={y1,y2,…,yn},找出X和Y的最长公共子序列。
Input
输入数据有多组,每组有两行 ,每行为一个长度不超过500的字符串(输入全是大写英文字母(A,Z)),表示序列X和Y。
Output
每组输出一行,表示所求得的最长公共子序列的长度,若不存在公共子序列,则输出0。
Sample Input
ABCBDAB BDCABA
Sample Output
4
code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int ans[510][510];
string a, b;
int n, m;
while(cin>>a>>b)
{
n = a.length();
m = b.length();
memset(ans, 0, sizeof(ans));
for(int i = 1;i<=n;i++)
{
for(int j = 1;j<=m;j++)
{
if(a[i-1] == b[j-1])
{
ans[i][j] = ans[i-1][j-1]+1;
}
else
{
ans[i][j] = max(ans[i-1][j], ans[i][j-1]);
}
}
}
cout<<ans[n][m]<<endl;
}
}