标签:
题意:给出一个字符串s,问至少加入多少个字母让它变成回文串
解题思路:求出该字符串与该字符串翻转后的最长公共子序列的长度,再用该字符串的长度减去最长公共子序列的长度即为所求
反思:因为题目所给的n的范围为3<=n<=5000,所以dp[][]数组如果开到dp[5005][5005],会超内存,此时应该就用滚动数组来优化
滚动数组的详细介绍http://blog.csdn.net/niushuai666/article/details/6677982
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 3301 Accepted Submission(s): 1140
#include<stdio.h> #include<string.h> char s[5005],w[5005]; int dp[2][5005]; int max(int a,int b) { if(a>b) return a; else return b; } int main() { int n,i,j,x,y; while(scanf("%d",&n)==1) { scanf("%s",&s); for(i=0;i<n;i++) w[i]=s[n-1-i]; w[i]=‘\0‘; memset(dp,0,sizeof(dp)); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { x=i%2; y=1-x; if(s[i-1]==w[j-1]) dp[x][j]=dp[y][j-1]+1; else dp[x][j]=max(dp[y][j],dp[x][j-1]); } } printf("%d\n",n-dp[n%2][n]); } }
标签:
原文地址:http://www.cnblogs.com/wuyuewoniu/p/4176173.html