For example: • ‘racecar’ is already a palindrome, therefore it can be partitioned into one group. • ‘fastcar’ does not contain any non-trivial palindromes, so it must be partitioned as (‘f’, ‘a’, ‘s’, ‘t’, ‘c’, ‘a’, ‘r’). • ‘aaadbccb’ can be partitioned as (‘aaa’, ‘d’, ‘bccb’).
Input
Input begins with the number n of test cases. Each test case consists of a single line of between 1 and 1000 lowercase letters, with no whitespace within.
Output
For each test case, output a line containing the minimum number of groups required to partition the input into groups of palindromes.
Sample Input
3 racecar fastcar aaadbccb
Sample Output
1 7 3
#include <queue>
#include <iostream>
#include<cstring>
#include<stdio.h>
#define maxn 1004
using namespace std;
int n,dp[maxn];
bool table[maxn][maxn];
char seq[maxn*2];
int trans(int i,int j)
{
if(table[i][j]) return 1;
return j-i+1;
}
/*
题目大义:
给定一个字符串,问最少能分解成多少个回文串
动态规划部分的思想很简单,
两重循环即可,如果预处理知道任意区间的
字符串是否为回文的即可。
重点是如何预处理得知任意区间的字符串是否为回文的,
这里采用枚举中心的方法,
但普通的方法仅对奇数长度的字符串有效,
而对于偶数长度的回文字符串却不奏效。
所以引入一种处理方法,
即在每两个字符之间插入一个特殊字符,
对新字符串进行扫描判断判断,
最终得出的回文区间i,j映射3到真实区间i>>1,(j-1)>>1;
(最终区间范围是0~l-1)
*/
int main()
{
ios::sync_with_stdio(false);
int t;scanf("%d",&t);
while(t--)
{
seq[0]='#';
scanf("%s",seq);
int l=strlen(seq);
for(int i=l;i>=0;i--) seq[(i<<1)+1]=seq[i];
for(int i=0;i<=2*l-1;i+=2) seq[i]='#';
memset(table,0,sizeof(table));
for(int i=0;i<=2*l-1;i++)
{
int ll=i,rr=i;
while(ll>=0&&rr<=2*l-1&&seq[ll]==seq[rr])
{
table[ll>>1][(rr-1)>>1]=true;
ll--,rr++;
}
}
/*
for(int i=0;i<l;i++)
for(int j=0;j<=i;j++)
if(table[j][i]) cout<<j<<" "<<i<<endl;*/
dp[0]=1;
for(int i=0;i<l;i++)
{
dp[i]=trans(0,i);
for(int j=0;j<i;j++)
{
if(!table[j+1][i]) continue;
dp[i]=min(dp[i],dp[j]+1);
}
}
printf("%d\n",dp[l-1]);
}
return 0;
}