题目链接http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2631
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
Kevin Waugh
dp入门题,可归为序列问题。即
给一行序列,要求满足条件的最优解
这类问题很多都可化为子问题,从头向后走到的第i个时,前面序列的最优解
有时这个dp[i]只与dp[i-1]相关,有时与1 ~ i-1都相关
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
int dp[1005];
char text[1005];
int Can(int l,int r){
int tag = 1;
for(int i = 0;i < (r-l)/2+1;i++){
if(text[l+i] != text[r-i]){
tag = 0;
break;
}
}
return tag;
}
int main(){
int n;
cin >> n;
while(n--){
text[0] = '0';
cin >> text+1;
dp[0] = 0;
int len = strlen(text)-1;
for(int i = 1;i <= len;i++){
int minx = 10000,tem;
for(int j = 0;j < i;j++){
if(Can(j+1,i)) tem = dp[j] + 1;
else tem = dp[j] + i - j;
minx = min(minx,tem);
}
dp[i] = minx;
}
cout << dp[len] << endl;
}
return 0;
}