最长公共子序列问题
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 <stdio.h>
#include <string.h>
int max(int a,int b)
{
if(a>b)
{
return a;
}
else return b;
}
int main()
{
char s1[501],s2[501];
while(~scanf("%s",s1))
{
scanf("%s",s2);
int n=strlen(s1);
int m=strlen(s2);
int c[n+1][m+1];
for(int i=0;i<=n;i++)
{
c[i][0]=0;
}
for(int i=0;i<=m;i++)
{
c[0][i]=0;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(s1[i-1]==s2[j-1])
{
c[i][j]=c[i-1][j-1]+1;
}
else
{
c[i][j]=max(c[i-1][j],c[i][j-1]);
}
}
}
printf("%d\n",c[n][m]);
}
return 0;
}
本文深入探讨了最长公共子序列问题,通过一个具体的编程实例,详细解释了如何使用动态规划算法来解决这一经典问题。文章提供了完整的代码实现,帮助读者理解算法背后的逻辑和步骤。
506

被折叠的 条评论
为什么被折叠?



