码迷,mamicode.com
首页 > 其他好文 > 详细

UVA11584-Partitioning by Palindromes(动态规划基础)

时间:2018-10-05 23:27:43      阅读:304      评论:0      收藏:0      [点我收藏+]

标签:while   required   ima   字符   sample   include   txt   BMI   状态   

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 }

 

UVA11584-Partitioning by Palindromes(动态规划基础)

标签:while   required   ima   字符   sample   include   txt   BMI   状态   

原文地址:https://www.cnblogs.com/npugen/p/9746263.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!