【题解】
dp转移的时候记录一下,然后倒着推出答案即可。
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #define LL long long 5 #define rg register 6 #define N 2000 7 using namespace std; 8 int n,m,tot,f[N][N],from[N][N][2]; 9 char s1[N],s2[N],ans[N]; 10 int main(){ 11 scanf("%s",s1+1); 12 scanf("%s",s2+1); 13 n=strlen(s1+1); m=strlen(s2+1); 14 for(rg int i=1;i<=n;i++) 15 for(rg int j=1;j<=m;j++) 16 if(s1[i]==s2[j]) f[i][j]=f[i-1][j-1]+1,from[i][j][0]=i-1,from[i][j][1]=j-1; 17 else{ 18 if(f[i-1][j]>f[i][j-1]) f[i][j]=f[i-1][j],from[i][j][0]=i-1,from[i][j][1]=j; 19 else f[i][j]=f[i][j-1],from[i][j][0]=i,from[i][j][1]=j-1; 20 } 21 while(n&&m){ 22 if(s1[n]==s2[m]) ans[++tot]=s1[n]; 23 int t1=from[n][m][0],t2=from[n][m][1]; 24 n=t1,m=t2; 25 } 26 for(rg int i=tot;i;i--) printf("%c",ans[i]); 27 return 0; 28 }