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
自己的代码:
#include <stdio.h> #include <string.h> char s[1010], revs[1010]; int d[1000][1000]; int min(int a, int b) { return a > b ? b : a; } int dp(int x, int y, int l) { if(x > y) return 0; if(d[x][y] > 0) return d[x][y]; if(memcmp(s+x, revs+l-y-1, sizeof(char) * (y - x + 1)) == 0) { return d[x][y] = 1; } d[x][y] = dp(x, x, l) + dp(x+1, y, l); for(int i = x + 1; i < y; i++) { d[x][y] = min(d[x][y], dp(x, i, l) + dp(i+1, y, l)); } return d[x][y]; } int main() { int n; scanf("%d", &n); while( n-- ) { memset(d, 0, sizeof(d)); scanf("%s", s); int len = strlen(s); strcpy(revs, s); strrev(revs); printf("%d\n", dp(0, len - 1, len)); } return 0; }
我的思路是 dp[x][y] = max{dp[x][i]+dp[i+1][y]| x<=i<=y},我自己在分析的时候认为递归调用只需要求出O(n^2)个值进行保存就可以,实际上这有点像是一个Catalan数。有很多的无用功用来计算子串,这样的子串有很多,而我却一直以为时间复杂度只有O(n^2),其实对于任何一个还没有求出结果的子串,他要访问它的所有划分O(n)个,而这样的子串共有O(n^2)个,因此它应该是一个O(n^3)的算法。
以后不能任务要找的中间结果就是时间复杂度了。
在网上找的答案:
#include <stdio.h> #include <string.h> char s[1010]; int d[1010]; int min(int a, int b) { return a > b ? b : a; } bool judge(int i, int j) { while(i < j) { if(s[i] != s[j]) return false; i++; j--; } return true; } int dp() { int len = strlen(s+1); d[0] = 0; for(int r = 1; r <= len; r++) { d[r] = 100000; for(int l = 1; l <= r; l++) { if(judge(l, r)) { d[r] = min(d[r], d[l-1] + 1); } } } return d[len]; } int main() { int n; scanf("%d", &n); while( n-- ) { scanf("%s", s+1); printf("%d\n", dp()); } return 0; }
这个算法计算的是前i个字符组成的串的答案,利用d[i] = min{d[j]+1 | s[j+1,i] is palindrome, j < i}。
总的来说,还是自己对复杂度不够敏感,对动态规划不够熟练,对子问题的划分不够优。需要更多的训练。
希望以后尽量可以自己思考得出答案。