Problem H: 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 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
//想法1:为每一个i到j的串提前预处理f[i][j]=1则是回文串。这样总的复杂度还是N^2 //然后dp,如果i-j是一个文回串,则dp[i]=min(dp[i],dp[j-1]+1) #include<cstdio> #include<iostream> #include<cstring> using namespace std; int f[1005][1005],l,dp[1005]; char s[1005]; void init() { memset(f,0,sizeof(f)); for(int i=1;i<=l;++i){ //中间想向外枚举 for(int j=0;i-j>0&&i+j<=l&&s[i-j]==s[i+j];++j){//奇数大小的串,是否为回文串 f[i-j][i+j]=1; } } for(int i=1;i<l;++i){ //中间想向外枚举 for(int j=0;i-j>0&&i+j+1<=l&&s[i-j]==s[i+j+1];++j){//偶数大小的串,是否为回文串 f[i-j][i+j+1]=1; } } } void solve() { scanf("%s",s+1); l=strlen(s+1); init(); dp[0]=0; dp[1]=1; for(int i=2;i<=l;++i){ dp[i]=i; for(int j=1;j<=i;++j){ if(f[j][i]){ //i-j回文 dp[i]=min(dp[i],dp[j-1]+1); } } } printf("%d\n",dp[l]); } int main() { int T; scanf("%d",&T); while(T--) { solve(); } return 0; }
//想法2: //直接dp,如果i-j是一个文回串(这里一个子函数判断),则dp[i]=min(dp[i],dp[j-1]+1) //按分析,dp需要n^2的复杂度,判断需要n,总计n^3,可是这居然更快,我猜是数据方面应该让判断很快就过去了 #include<cstdio> #include<iostream> #include<cstring> using namespace std; char str[1005]; int dp[1005]; bool Check(int l, int r) { while (l < r) { if (str[l] != str[r]) return false; l++; r--; } return true; } int main() { int T, i, j; scanf("%d", &T); while (T--) { scanf("%s", str + 1); int len = strlen(str + 1); for (i = 1; i <= len; i++) { dp[i] = dp[i - 1] + 1; for (j = 1; j < i; j++) if (Check(j, i)) dp[i]=min(dp[j - 1] + 1, dp[i]);//i-j回文 } printf("%d\n", dp[len]); } return 0; }