专题测试三 贪心与动态规划 E - Partitioning by Palindromes
- 题目
We say a sequence of characters is a palindrome 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
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 - 思路
dp,dp[i]存储从第一个到第i个字母中回文数量,每次检查(j,i)一段,如果这一段是回文串,那么就有dp[i]=min(dp[i],dp[j-1]+1) - 代码
#include<cstdio> #include<iostream> #include<string> #include<cstring> #include<algorithm> using namespace std; char str[1010]; int f[1010]; bool judge(int x,int y) { while(x <= y) { if(str[x] != str[y]) return 0; x++; y--; } return 1; } int main() { int len, i, j, n; scanf("%d",&n); while(n--) { scanf("%s",str); len = strlen(str); f[0]=1; for(i = 0; i < len; i++) { f[i] = 1145141919; for(j = 0; j <= i; j++) if(judge(j,i)) f[i] = min(f[i], f[j-1]+1); } printf("%d\n",f[len-1]); } return 0; }