# Partitioning by Palindromes UVA - 11584（最小回文串分解DP）

We say a sequence of charactersis a palindrome if itis the same written forwardsand backwards. For example,‘racecar’ is a palindrome, but‘fastcar’ is not.

A partition of a sequence ofcharacters is a list of one ormore disjoint non-empty groupsof consecutive characters whoseconcatenation yields the initialsequence. For example, (‘race’,‘car’) is a partition of ‘racecar’into two groups.

Given a sequence of characters,we can always create a partitionof these characters suchthat each group in the partitionis a palindrome! Given this observationit is natural to ask:what is the minimum number ofgroups needed for a given stringsuch that every group is a palindrome?

For example:• ‘racecar’ is already apalindrome, therefore itcan be partitioned intoone group.• ‘fastcar’ does not containany non-trivial palindromes,so it must be partitionedas (‘f’, ‘a’, ‘s’, ‘t’,‘c’, ‘a’, ‘r’).• ‘aaadbccb’ can be partitionedas (‘aaa’, ‘d’, ‘bccb’).

#### Input

Input begins with the number n of test cases. Each test case consists of a single line of between 1 and1000 lowercase letters, with no whitespace within.

#### Output

For each test case, output a line containing the minimum number of groups required to partition theinput into groups of palindromes.

3

racecar

fastcar

#### SampleOutput

1

7

3

Code：

#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
string s;
int check(int x,int y){
while(x<y){
if(s[x]!=s[y]) return 0;
x++;
y--;
}
return 1;
}
int d[1005];
int main(){
int t;

cin>>t;
getchar();
while(t--){
getline(cin,s);
int len=s.length();
d[0]=1;
for(int i=1;i<len;i++){
d[i]=d[i-1]+1;
for(int j=i-1;j>=0;j--){
if(check(j,i))	d[i]=min(d[i],d[j-1]+1);
}
}
cout<<d[len-1]<<endl;
}

} 

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120