最长公共子序列
时间限制:3000 ms | 内存限制:65535 KB
难度:3
描述
咱们就不拐弯抹角了,如题,需要你做的就是写一个程序,得出最长公共子序列。
tip:最长公共子序列也称作最长公共子串(不要求连续),英文缩写为LCS(Longest Common Subsequence)。其定义是,一个序列 S ,如果分别是两个或多个已知序列的子序列,且是所有符合此条件序列中最长的,则 S 称为已知序列的最长公共子序列。
输入
第一行给出一个整数N(0<N<100)表示待测数据组数
接下来每组数据两行,分别为待测的两组字符串。每个字符串长度不大于1000.
输出
每组测试数据输出一个整数,表示最长公共子序列长度。每组结果占一行。
样例输入
2asdfadfsd123abcabc123abc
样例输出
36
程序代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int c[1001][1001];
int lcs(char *s1,char *s2)
{
int m=strlen(s1);
int n=strlen(s2);
int i,j;
c[0][0]=0;
for(i=1;i<=m;i++)
{
c[i][0]=0;
}
for(j=1;j<=n;j++)
{
c[0][j]=0;
}
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
if(s1[i-1]==s2[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];
}
}
}
return c[m][n];
}
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
char a[1008],b[1008];
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
scanf("%s%s",a,b);
printf("%d\n",lcs(b,a));
}
system("pause");
return 0;
}