Solve the longest public subsequence problem:
Solution:
For example, the given two sequences are x = <A, B, C, B, D, a, B> and Y = <B, D, C, A, B, a>. The results calculated by the algorithms lcs_length and LCs are shown in:
The template can be written
void lcss(){ int i,j; int sizex=str1.length(); int sizey=str2.length(); for(i=0;i<=sizex;i++) lcs[i][0]=0; for(i=0;i<=sizey;i++) lcs[0][i]=0; for(i=1;i<=sizex;i++) for(j=1;j<=sizey;j++) { if(str1[i-1]==str2[j-1]) lcs[i][j]=lcs[i-1][j-1]+1; else lcs[i][j]=lcs[i-1][j]>=lcs[i][j-1]?lcs[i-1][j]:lcs[i][j-1]; } cout<<lcs[sizex][sizey]<<endl; }
View code
You can also compress the array:
memset(lcs,0,sizeof(lcs)); for(i=1;i<=n;i++) for(j=1;j<=n;j++) { if(str1[i-1]==str2[j-1]) lcs[i%2][j]=lcs[(i-1)%2][j-1]+1; else lcs[i%2][j]=lcs[(i-1)%2][j]>lcs[i%2][j-1]?lcs[(i-1)%2][j]:lcs[i%2][j-1]; } printf("%d\n",lcs[n%2][n]) ;
View code
Training Questions:
Http://acm.hdu.edu.cn/diy/contest_show.php? Cid = 24575
August 26-Dynamic Planning of LCS