最长公共子序列详解思路总结:https://blog.csdn.net/hrn1216/article/details/51534607
最长公共子序列问题
Time Limit: 1000 ms
Memory Limit: 65536 KiB
Problem Description
给定两个序列X=
Input
输入数据有多组,每组有两行 ,每行为一个长度不超过500的字符串(输入全是大写英文字母(A,Z)),表示序列X和Y。
Output
每组输出一行,表示所求得的最长公共子序列的长度,若不存在公共子序列,则输出0。
Sample Input
ABCBDAB BDCABA
Sample Output
4
1.首先知道求最长公共子序列的原理:
#include <algorithm>
#include <stdio.h>#include <string.h>
#include <math.h>
#include<iostream>
using namespace std;
int main()
{
int i,j,len1,len2,c[502][502] = {0};
char x[502],y[502];
while(scanf("%s\n%s",x,y) != EOF)
{
len1 = strlen(x);
len2 = strlen(y);
for(i = 1;i <= len1;i++)
{
for(j = 1;j <= len2;j++)
{
if(x[i-1] == y[j-1])
c[i][j] = c[i-1][j-1] + 1;
else
{
if(c[i-1][j] > c[i][j-1])
c[i][j] = c[i-1][j];
else
c[i][j] = c[i][j-1];
}
}
}
cout<<c[len1][len2]<<endl;
}
return 0;
}