c - error in finding the longest common sub sequence between two strings -
#include <stdio.h> #include <string.h> int m,n,a,c[20][20]; char x[15],y[15],b[20][20]; void print_lcs(int i,int j) { if(i==0 || j==0) return; if(b[i][j]=='c') { print_lcs(i-1,j-1); printf("%c",x[i-1]); } else if(b[i][j]=='u') print_lcs(i-1,j); else print_lcs(i,j-1); } void lcs() { int i,j; m=strlen(x); n=strlen(y); for(i=0;i<=m;i++) c[i][0]=0; for(i=0;i<=n;i++) { printf("0\t"); c[0][i]=0; } printf("\n"); for(i=1;i<=m;i++) { printf("0\t"); for(j=1;j<=n;j++) { if(x[i-1]==y[i-1]) { c[i][j]=c[i-1][j-1]+1; b[i][j]='c'; printf("%dc\t",c[i][j]); } else if(c[i-1][j]>=c[i][j-1]) { c[i][j]=c[i-1][j]; b[i][j]='u'; printf("%du\t",c[i][j]); } else { c[i][j]=c[i][j-1]; b[i][j]='l'; printf("%dl\t",c[i][j]); } } printf("\n\n"); } printf("\nlongest common subsequence is:"); print_lcs(m,n); printf("\n"); printf("\nthe length of subsequence is:%d",c[m][n]); } int main() { printf("enter 1st sequence:"); scanf("%s",&x); printf("\nenter 2nd sequence:"); scanf("%s",&y); lcs(); printf("\n"); getch(); return 0; }
the function print_lcs starts m,n , used print subsequence. lcs function find lcs 2 d array b has characters c,u,l meaning top left, upper , left elements. output not answer, gives subsequence shorter actual answer.
for input seq 1=1000101011
& seq 2=00011101
lcs 001
whereas actual answer 0001101
Comments
Post a Comment