Dynamic Programming algorithm
#include <iostream>#include<string.h>#include<algorithm>#include<math.h>using namespacestd;#defineMaxstrlen 20intLcs (CharX[],CharY[],intPath[][maxstrlen])//To find the longest common subsequence of the sequence x and Y, the path save route points to facilitate printing of common sub-sequences{ intI, J; intLen1=strlen (x)-1; intLen2=strlen (Y)-1; int**c=New int*[len1+1]; for(i=0; i<=len1; i++) C[i]=New int[len2+1]; for(i=0; i<=len1; i++) c[i][0]=0; for(i=0; i<=len2; i++) c[0][i]=0; for(i=1; i<=len1; i++) for(j=1; j<=len2; J + +)//starting from x[1],y[1] { if(x[i]==Y[j]) {C[i][j]=c[i-1][j-1]+1; PATH[I][J]=1; } Else if(c[i-1][j]>=c[i][j-1]) {C[i][j]=c[i-1][j]; PATH[I][J]=2; } Else{C[i][j]=c[i][j-1]; PATH[I][J]=3; } } returnc[len1][len2];}voidPrintlcs (intIintJCharX[],intPath[][maxstrlen])//print the longest common sub-sequence{ if(i==0|| j==0) return; if(path[i][j]==1) {Printlcs (i-1, J-1, x, Path); cout<<X[i]; } Else if(path[i][j]==2) Printlcs (i-1, J, x, Path); ElsePrintlcs (i, J-1, x, Path); }voidMain () {CharA[maxstrlen]; CharB[maxstrlen]; intPath[maxstrlen][maxstrlen]; Gets (a+1);//A[0] Not counting, starting from a[1]Gets (b +1);//B[0] Not counting, starting from b[1]cout<<lcs (A, B, path) <<Endl; cout<<"the longest common subsequence:"; Printlcs (Strlen (a)-1, strlen (b)-1, A, path); cout<<Endl; }
Recursive algorithm
#include <iostream>using namespacestd;#defineMaxstrlen 20//Recursive algorithmintLcs (Char*STR1,Char*str2) { if(*str1==' /'|| *str2==' /') return 0; if(*str1==*str2)returnLcs (str1+1, str2+1)+1; Else if(Lcs (str1+1, str2) >lcs (str1, str2+1)) returnLcs (str1+1, STR2); Else returnLcs (STR1, str2+1); }voidMain () {CharA[maxstrlen]; CharB[maxstrlen]; Gets (a); Gets (b); cout<<lcs (A, b) <<Endl; }
LCS Algorithm Implementation