题目链接:http://poj.org/problem?id=1159
题目大意:给你一个字符串,问最少添加多少个字符就能使其成为一个回文串。
ps:以前做过的一个题目跟这个很相似,但显然这个的要求的条件更少,所以很容易确定状态和状态转移。但是这个题目用int会超内存,所以只能用short就能AC了,这里wa了两次,注意简单题目也要认真对待才行啊。
代码:
#include <iostream> #include <cstdio> #include <cstring> using namespace std; short dp[5005][5005]; char str[5005]; int main(){ int n; while(scanf("%d",&n)!=EOF){ scanf("%s",str+1); for(int l=1;l<=n-1;++l){ for(int i=1;i+l<=n;++i){ int j=i+l; if(str[i]==str[j]){ dp[i][j]=dp[i+1][j-1]; }else{ dp[i][j]=min(dp[i][j-1]+1,dp[i+1][j]+1); } } } printf("%d\n",dp[1][n]); } return 0; }
本文介绍了解决 POJ 1159 题目的方法,该题要求找出使任意字符串成为回文串所需的最少字符添加数。通过动态规划算法实现,特别注意使用 short 类型来避免内存溢出。
1022

被折叠的 条评论
为什么被折叠?



