题解:最长公共子序列+路径记录
设dp[i][j]经典转移,用path[i][j]记录路径,记录公共序列出现的位置,倒着向前找,如果有字符相同并且dp[i][j]是从dp[i-1][j-1]转移过来的,那么这就一定是公共子序列的一部分,记录后输出剩余的部分即可。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <cstring>
using namespace std;
char ch1[110], ch2[110];
int dp[110][110];
bool b1[110], b2[110];
int main(){
while(scanf("%s%s", ch1+1, ch2+1) != EOF){
memset(dp, 0, sizeof dp);
memset(b1, 0, sizeof b1);
memset(b2, 0, sizeof b2);
int len1 = strlen(ch1+1);
int len2 = strlen(ch2+1);
for(int i = 1; i <= len1; i ++){
for(int j = 1; j <= len2; j ++){
if(ch1[i] == ch2[j])
dp[i][j] = dp[i-1][j-1] + 1;
else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
for(int i = len1, j = len2; dp[i][j] != 0; ){
if(ch1[i] == ch2[j] && dp[i][j] == dp[i-1][j-1]+1){
b1[i] = 1, b2[j] = 1;
i --, j --;
}
else if(dp[i][j] == dp[i-1][j]) i --;
else j --;
}
int i = 1, j = 1;
for(int k = 1; k <= dp[len1][len2]; k ++){
while(!b1[i]) printf("%c", ch1[i++]);
while(!b2[j]) printf("%c", ch2[j++]);
printf("%c", ch1[i]),i ++, j ++;
}
while(i <= len1) printf("%c", ch1[i++]);
while(j <= len2) printf("%c", ch2[j++]);
printf("\n");
}
return 0;
}