最长公共子序列问题
Description
给定两个序列 X={x1,x2,…,xm} 和 Y={y1,y2,…,yn},找出X和Y的最长公共子序列。
Input
输入数据有多组,每组有两行 ,每行为一个长度不超过500的字符串(输入全是大写英文字母(A,Z)),表示序列X和Y。
Output
每组输出一行,表示所求得的最长公共子序列的长度,若不存在公共子序列,则输出0。
Sample
Input
ABCBDAB BDCABA
Output
4
1 #include<stdio.h> 2 3 int c[1000][1000]; 4 int main() 5 { 6 char x[1000]; 7 char y[1000]; 8 while(gets(x)) 9 { 10 gets(y); 11 int i,j; 12 int len1 = strlen(x); 13 int len2 = strlen(y); 14 for(i=1; i<=len1; i++) 15 { 16 for(j=1; j<=len2; j++) 17 { 18 if(x[i-1] == y[j-1]) 19 c[i][j] = c[i-1][j-1] + 1; 20 else 21 { 22 if(c[i-1][j]>c[i][j-1])//去掉x和y中最后两项后的最大子序列 23 c[i][j] = c[i-1][j]; 24 else 25 c[i][j] = c[i][j-1]; 26 } 27 } 28 } 29 printf("%d\n",c[len1][len2]); 30 } 31 return 0; 32 }

浙公网安备 33010602011771号