Problem UVA11584-Partitioning by Palindromes
Accept: 1326 Submit: 7151
Time Limit: 3000 mSec
Problem Description
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[i]的含义是前i个字符组成的字符串所能划分成的最少回文串的个数,定义好这个状态就很简单了,dp[i]肯定是从dp[j]转移过来(j<i)并且需要j+1到i是回文串,此时
dp[i] = min(dp[i], dp[j] + 1),方程有了,边界也没啥困难的地方。
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 const int maxn = 1000 + 10; 6 const int INF = 0x3f3f3f3f; 7 8 char str[maxn]; 9 10 int is_palindromes[maxn][maxn]; 11 int dp[maxn]; 12 13 int Is_palindromes(int j, int i) { 14 if (j >= i) return 1; 15 if (is_palindromes[j][i] != -1) return is_palindromes[j][i]; 16 17 if (str[i] == str[j]) { 18 return is_palindromes[j][i] = Is_palindromes(j + 1, i - 1); 19 } 20 else return is_palindromes[j][i] = 0; 21 } 22 23 int main() 24 { 25 //freopen("input.txt", "r", stdin); 26 int iCase; 27 scanf("%d", &iCase); 28 while (iCase--) { 29 scanf("%s", str + 1); 30 memset(is_palindromes, -1, sizeof(is_palindromes)); 31 dp[0] = 0; 32 int len = strlen(str + 1); 33 for (int i = 1; i <= len; i++) { 34 dp[i] = i; 35 for (int j = 0; j < i; j++) { 36 if (Is_palindromes(j + 1, i)) dp[i] = min(dp[i], dp[j] + 1); 37 } 38 } 39 printf("%d\n", dp[len]); 40 } 41 return 0; 42 }
原文地址:https://www.cnblogs.com/npugen/p/9746263.html
时间: 2024-10-24 23:21:38