NYOJ练习题 Splits the string (简单动态规划)
2013-10-20 17:29
411 查看
Splits the string
时间限制:1000 ms | 内存限制:65535 KB描述
Hrdv is interested in a string,especially the palindrome string.So he wants some palindrome string.
A sequence of characters is a palindrome if it is the same written forwards and backwards. For example, 'abeba' is a palindrome, but 'abcd' 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.
输入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.
样例输入
racecar fastcar aaadbccb
样例输出
1 7 3
题意:给定一个字符串,求最少需要几个回文子串组成此字符串。
解题思路:用dp[i] 记录从0到当前i位置这一段最少由几个回文子串组成,动态转移方程:dp[i] = min(dp[i],dp[j-1]+1);
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; char str[1010]; int dp[1010]; bool judge(int x,int y) //判断是不是回文串 { while(x <= y) { if(str[x] != str[y]) return false; x++; y--; } return true; } int main() { int len, i, j; while(gets(str) != NULL) { len = strlen(str); for(i = 0; i < len; i++) { dp[i] = i + 1; //假设前面的都不能组成回文串 for(j = 0; j <= i; j++) if(str[j] == str[i] && judge(j,i)) dp[i] = min(dp[i], dp[j-1]+1); } printf("%d\n",dp[len-1]); } return 0; }
相关文章推荐
- nyoj 子串和 44 (简单动态规划)
- NYOJ 104 矩阵最大和 - 简单动态规划
- NYOJ 330 一个简单的数学题【数学题】
- nyoj244 16进制的简单运算
- NYOJ 330 一个简单的数学题
- NYOJ 555 相反输出【简单题】
- NYOJ--49(动态规划)-题目----------------------------- 开心的小明
- NYOJ - 16进制的简单运算
- 简单整理(nyoj 132 && 744 && tyvj 1001 && 1141 && 1170 && 1067 && 1015)
- NYOJ 330 一个简单的数学题
- nyoj 16进制的简单运算
- HDOJ1574 RP问题 动态规划 简单DP
- NYOJ - 76 - 超级台阶(动态规划)
- 动态规划练习题-23(大盗阿福)
- poj 1157 简单动态规划
- NYOJ-244-16进制的简单运算-2013年10月17日17:19:41
- nyoj--61--传纸条(一)(动态规划)
- C++简单练习题3——汉诺塔问题
- codeforce 416/B 动态规划简单题
- 【动态规划练习题】 学生宿舍(重庆一中高2018级信息学竞赛测验10) 解题报告