题目链接:http://acm.hust.edu.cn/vjudge/problem/34398
题意:给出一个字符串,把它划分成尽量少的回文串。
没想到用O(n3)的暴力也能过,看来是数据太水。
思路:dp[i]表示前i个字符能划分成的最小回文串数,设j<i,如果s[j+1~i]为回文串,那么dp[i]即为MIN(dp[j]+1),状态转移也就出来了,详见代码。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>
#include<iostream>
using namespace std;
const int maxn = 1000 + 5;
int dp[maxn];
char s[maxn];
inline bool judge(int l, int r) //判断回文串
{
while(l < r) {
if (s[l] != s[r]) return false;
l++, r--;
}
return true;
}
int main()
{
int n;
scanf("%d",&n);
while(n--) {
scanf("%s",s+1);
int len = strlen(s+1);
dp[0] = 0;
for(int i = 1; i <= len; i++) {
dp[i] = i;
for(int j = 0; j < i; j++) {
if (judge(j+1,i))
dp[i] = min(dp[i], dp[j] + 1);
}
}
printf("%d\n",dp[len]);
}
}