Common Subsequence
The program input is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct. For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line.
abcfbc abfcab programming contest abcd mnp
4 2 0
#include <stdio.h>
#include <string.h>
int a[1000][1000];
int b[1000][1000];
void LCSlength(int m,int n,char x[],char y[])
{
int i,j;
for(i=1;i<=m;i++) a[i][0]=0;
for(i=1;i<=n;i++) a[0][i]=0;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(x[i]==y[j]){
a[i+1][j+1]=a[i][j]+1;
b[i+1][j+1]=1;
}else if(a[i][j+1]>=a[i+1][j]){
a[i+1][j+1]=a[i][j+1];
b[i+1][j+1]=2;
} else{
a[i+1][j+1]=a[i+1][j];
b[i+1][j+1]=3;
}
}
}
}
int main()
{
char x[1000];
char y[1000];
char z[10000];
int m,n;
while(gets(z))
{
memset(x,0,sizeof(x));
memset(y,0,sizeof(y));
for(m=0;m<strlen(z);m++)
{
if(z[m]!=' ')
x[m]=z[m];
else
break;
}
int i=0;
for(n=m+1;n<strlen(z);n++)
{
if(z[n]!=' ')
y[i++]=z[n];
}
LCSlength(m,i+1,x,y);
printf("%d\n",a[m][i+1]);
}
return 0;
}
887




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



