if(s[x]==s[y]) dp[x][y]=dp[x+1][y-1]+2
else dp[x][y]=min(dp[x+1][y],dp[x][y-1])+2
方案分开来求
#include <iostream> #include <cstdio> #include <cstring> #include <set> #include <algorithm> using namespace std; char s[1010]; int dp[1010][1010]; int x,y,ac,l; string ans; int DP(){ if(dp[x][y]!=-1) return dp[x][y]; if(x>y) return dp[x][y]=0; if(x==y) return dp[x][y]=1; int ret=10000; if(s[x]==s[y]){ x++,y--; ret=min(ret,DP()+2); x--,y++; }else{ x++; ret=min(ret,DP()+2); x--; y--; ret=min(ret,DP()+2); y++; } //cout<<x<<" "<<y<<" "<<ret<<endl; return dp[x][y]=ret; } void gao(){ if(x>y) return; if(x==y) {ans+=s[x];return;} //cout<<x<<" "<<y<<" "<<ac<<endl; if(s[x]==s[y]){ ac-=2; ans+=s[x]; x++,y--; gao(); }else if(dp[x][y-1]+2==ac&&dp[x][y]==dp[x][y-1]+2){ ac-=2; ans+=s[y]; y--; gao(); }else if(dp[x+1][y]+2==ac&&dp[x][y]==dp[x+1][y]+2){ ac-=2; ans+=s[x]; x++; gao(); } } void solve(){ l=strlen(s+1); memset(dp,-1,sizeof dp); x=1,y=l; int ret=DP(); printf("%d ",ret-l); ac=ret; ans=""; x=1,y=l; gao(); int len=ans.length(); for(int i=0;i<len;i++) putchar(ans[i]); int start=ret&1 ? len-2:len-1; for(int i=start;i>=0;i--) putchar(ans[i]); putchar(' '); } int main(){ //freopen("10453.txt","r",stdin); while(~scanf("%s",s+1)){ solve(); } return 0; }