先跑一遍lcs得到最长公共子序列长度,再倒着跑一遍记录路径,即dp[i][j]刚开始发生改变的地方
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1010;
char s1[maxn],s2[maxn],path[maxn];
int dp[maxn][maxn];
int len1,len2;
void lcs(char s1[], char s2[])
{ //cout<<strlen(s1)<<endl<<strlen(s2)<<endl;
int len1 = strlen(s1),len2 = strlen(s2);
for(int i = 0; i<len1; i++){
for(int j = 0; j<len2; j++){
if(s1[i]==s2[j]){
dp[i+1][j+1]=dp[i][j]+1;
}
else{
dp[i+1][j+1]=max(dp[i+1][j],dp[i][j+1]);
}
}
}
}
void work(char s1[],char s2[])
{
int plen = 0,len1 = strlen(s1),len2 = strlen(s2);
int i = len1 -1 ;
int j= len2 -1;
while(i>=0&&j>=0){
if(s1[i]==s2[j]){
path[plen++] = s1[i];
i--,j--;
}
else if(dp[i+1][j]>=dp[i][j+1]){
j--;
}
else {
i--;
}
}
reverse(path,path+plen);
}
int main()
{
scanf("%s",s1);
scanf("%s",s2);
len1 = strlen(s1);
len2 = strlen(s2);
if(len1<=len2) lcs(s1,s2),work(s1,s2);
else lcs(s2,s1),work(s2,s1);//cout<<dp[len1][len2]<<endl;
puts(path);
return 0;
}