https://acm.nyist.net/JudgeOnline/problem.php?pid=37
/* 求一个字符串要变成回文串的需要添加的字符最少个数 1. 字符串s1反转得到s2 2. 求 s1和s2 的最长公共子序列长度 len 3. 结果为 :strlen(s1)- len */ /*************************** # 2013-10-29 13:38:54 # Time: MS Memory: K # Author: zyh # Status: Accepted ***************************/ #include<iostream> #include<stdio.h> #include<string.h> #include<stdlib.h> #include<algorithm> #define Max(a,b) (a)>(b)?(a):(b) using namespace std; char s1[1010],s2[1010]; int c[1010][1010]; int LCS(char *a,char *b) { int i,j,len = strlen(a); //for(i=0;i<=len;i++) c[i][0] = c[0][i] = 0; for(i=1;i<=len;i++){ for(j=1;j<=len;j++){ if(a[j-1]==b[i-1]) c[i][j] = c[i-1][j-1] + 1; else c[i][j] = Max(c[i-1][j],c[i][j-1]); } } return c[len][len]; } int main() { int n,i,j,len; scanf("%d",&n);getchar(); while(n--) { memset(c,0,sizeof(c)); gets(s1); len = strlen(s1); for(i=len-1,j=0;i>=0;i--,j++) s2[j]=s1[i]; s2[j] = '\0'; printf("%d\n",len-LCS(s1,s2)); } return 0; } /* 2 Ab3bd 12341 */