A typical variant of LCS Algo.
The key, the dp[][] array contains enough message to determine the LCS, not only the length, but all of the LCS Candidate, we can backtrack to the find all of LCS.
For backtrack, one criteria is
dp[i-1][j]==dp[i][j]-1 && dp[i][j-1]==dp[i][j]-1
Another is
dp[i][j]==dp[i-1][j-1]+1 && str1[i]==str2[j]
Both is OK, this first one is used.
//
#include <cstdio>#include <cstring>#include <algorithm>structmynode{intx, y; };#define MAXSIZEintDp[maxsize][maxsize];mynode Pos[maxsize];CharStr1[maxsize], str2[maxsize];intMain () {#ifndef Online_judgeFreopen ("In.txt","R", stdin);#endif intI,j,k,ch,len1,len2,len3; while(scanf("%s%s", str1+1, str2+1)==2) {len1=strlen(str1+1), len2=strlen(str2+1); for(i=1; i<=len1;++i) { for(Ch=str1[i], j=1; j<=len2;++j) {if(Ch==str2[j]) dp[i][j]=1+dp[i-1][j-1];Elsedp[i][j]=STD:: Max (dp[i][j-1],dp[i-1][J]); } } for(I=len1, J=len2, len3=dp[len1][len2]-1; len3>=0;--len3) { while(1) { for(k=j;len3!=dp[i][k-1];--K) {}if(len3==dp[i-1][k]) {pos[len3]={i,k}; I.-j=k-1; Break; }Else{--i;k=j; }}} Len3=dp[len1][len2]; pos[len3]={len1+1, len2}; for(i=1, j=1, k=0; k<=len3;++k,++i,++j) { for(; i<pos[k].x;++i)Putchar(Str1[i]); for(; j<pos[k].y;++j)Putchar(Str2[j]);Putchar(Str2[j]); }Putchar(' \ n '); }return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. Ps. If in any-to-improment can be achieved, better performance or whatever, it'll be well-appreciated-let me know, thank s in advance.
HDU 1503, LCS variants, find a LCS, not just the length, backtrack to find LCS, no extra markup