https://vjudge.net/problem/UVA-10453
给出一个字符串,问最少添加几个字符使其变为回文串,并输出任意一种答案。就是一个类似于LCS的题目,而且简化了一下,只会出现三种情况。令f[i][j]表示这个字符串i~j位的答案,当si==sj f[i][j]=f[i+1][j-1] ; 否则f[i][j]=MIN{f[i+1][j],f[i][j-1]}+1, 取一个最小值就是答案,最后递归输出一下。
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 #include<algorithm> 5 #include<vector> 6 using namespace std; 7 #define inf 0x3f3f3f3f 8 char s[1005]; 9 int f[1005][1005],N; 10 void out(int l,int r) 11 { 12 if(r<l) return; 13 if(l==r){printf("%c",s[l]);return ;} 14 if(s[l]==s[r]&&f[l][r]==f[l+1][r-1]){ 15 printf("%c",s[l]); 16 out(l+1,r-1); 17 printf("%c",s[l]); 18 } 19 else{ 20 if(f[l][r]==f[l][r-1]+1){ 21 printf("%c",s[r]); 22 out(l,r-1); 23 printf("%c",s[r]); 24 } 25 else{ 26 printf("%c",s[l]); 27 out(l+1,r); 28 printf("%c",s[l]); 29 } 30 } 31 } 32 int main() 33 { 34 int N,M,i,j,k; 35 while(gets(s+1)){ 36 int n=strlen(s+1);N=n; 37 //if(!n){puts("0");continue;} 38 memset(f,0,sizeof(f)); 39 for(int len=2;len<=n;++len) 40 { 41 for(i=1,j=len;j<=n;++i,++j) 42 { 43 f[i][j]=inf; 44 if(s[i]==s[j]) f[i][j]=min(f[i][j],f[i+1][j-1]); 45 f[i][j]=min(f[i][j],1+min(f[i+1][j],f[i][j-1])); 46 } 47 } 48 cout<<f[1][n]<<' '; 49 out(1,n); 50 puts(""); 51 } 52 return 0; 53 }