最长公共子序列问题
最长公共子序列问题
Time Limit: 1000 ms Memory Limit: 65536 KiB
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
Hint
Source
#include<bits/stdc++.h>
using namespace std;
#define N 550
#define M 20110
#define inf 0x3f3f3f3f
int main()
{
char x[N], y[N];
while(gets(x) != NULL)
{
gets(y);
int a[N][N] = {0};
int len1 = strlen(x);
int len2 = strlen(y);
for(int i = 1; i <= len1; i++)
{
for(int j = 1; j <= len2; j++)
{
if(x[i-1] == y[j-1])
{
a[i][j] = a[i-1][j-1]+1;
}
else
a[i][j] = max(a[i-1][j],a[i][j-1]);
}
}
cout << a[len1][len2] << endl;
}
}