2014-08-27 11:43:18
Problem H: Partitioning by Palindromes
We say a sequence of characters is apalindrome if it is the same written forwards and backwards. For example, 'racecar' is a palindrome, but 'fastcar' is not.
A partition of a sequence of characters is a list of one or more disjoint non-empty groups of consecutive characters whose concatenation yields the initial sequence. For example, ('race', 'car') is a partition of 'racecar' into two groups.
Given a sequence of characters, we can always create a partition of these characters such that each group in the partition is a palindrome! Given this observation it is natural to ask: what is the minimum number of groups needed for a given string such that every group is a palindrome?
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 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.
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
思路:dp[i]表示把前 i 个字符划分成最少回文串的个数。dp[i] = min(dp[j] + 1) (0 <= j < i,s[j+1 ~ i]是回文串),枚举型递推动规
1 /************************************************************************* 2 > File Name: 11584.cpp 3 > Author: Nature 4 > Mail: 564374850@qq.com 5 > Created Time: Tue 26 Aug 2014 09:23:34 PM CST 6 ************************************************************************/ 7 8 #include <cstdio> 9 #include <cstring> 10 #include <cstdlib> 11 #include <cmath> 12 #include <iostream> 13 #include <algorithm> 14 using namespace std; 15 const int INF = 1 << 29; 16 17 int n; 18 int len; 19 int dp[1005]; 20 int judge[1005][1005]; 21 char s[1005]; 22 23 void Pre_process(){ 24 memset(judge,0,sizeof(judge)); 25 for(int i = 1; i <= len; ++i){ 26 for(int j = 0; j < len; ++j){ 27 if(i - j < 1 || i + j > len || s[i - j] != s[i + j]) 28 break; 29 judge[i - j][i + j] = 1; 30 } 31 for(int j = 0; j < len; ++j){ 32 if(i - j - 1 < 1 || i + j > len || s[i - j - 1] != s[i + j]) 33 break; 34 judge[i - j - 1][i + j] = 1; 35 } 36 } 37 } 38 39 int main(){ 40 scanf("%d",&n); 41 while(n--){ 42 scanf("%s",s + 1); 43 len = strlen(s + 1); 44 Pre_process(); 45 dp[0] = 0; 46 for(int i = 1; i <= len; ++i){ 47 dp[i] = INF; 48 for(int j = 0; j < i; ++j) if(judge[j + 1][i]){ 49 dp[i] = min(dp[i],dp[j] + 1); 50 } 51 } 52 printf("%d\n",dp[len]); 53 } 54 return 0; 55 }