Partitioning by Palindromes UVA - 11584(最小回文串分解DP)

    We say a sequence of charactersis a palindrome if itis the same written forwardsand backwards. For example,‘racecar’ is a palindrome, but‘fastcar’ is not.

    A partition of a sequence ofcharacters is a list of one ormore disjoint non-empty groupsof consecutive characters whoseconcatenation yields the initialsequence. For example, (‘race’,‘car’) is a partition of ‘racecar’into two groups.

    Given a sequence of characters,we can always create a partitionof these characters suchthat each group in the partitionis a palindrome! Given this observationit is natural to ask:what is the minimum number ofgroups needed for a given stringsuch that every group is a palindrome?

    For example:• ‘racecar’ is already apalindrome, therefore itcan be partitioned intoone group.• ‘fastcar’ does not containany non-trivial palindromes,so it must be partitionedas (‘f’, ‘a’, ‘s’, ‘t’,‘c’, ‘a’, ‘r’).• ‘aaadbccb’ can be partitionedas (‘aaa’, ‘d’, ‘bccb’).

Input

Input begins with the number n of test cases. Each test case consists of a single line of between 1 and1000 lowercase letters, with no whitespace within.

Output

For each test case, output a line containing the minimum number of groups required to partition theinput into groups of palindromes.

Sample Input

3

racecar

fastcar

aaadbccb

SampleOutput

1

7

3

题目大意&&解题思路:

给定一个字符串,使其分解为若干个回文串,输出最小的分解数。利用动态规划思想,d[i] 表示s[0,i]所能分解成的回文串最小数量,d[0]=1是必然的,意思是从头开始分解,d[i]有两种情况,若存在一个0<j<i使得s[j,i]为回文串,那么s[j-1]后的串s[i,j]就单独构成了一个回文串,d[i]无非是d[i-1]的基础上加1;不然,d[i]=d[i-1]+1,代表开辟一个新的分解小串。

Code:

#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
string s;
int check(int x,int y){
	while(x<y){
		if(s[x]!=s[y]) return 0;
		x++;
		y--;
	}
	return 1;
}
int d[1005]; 
int main(){
	int t;

	cin>>t;
	getchar();
	while(t--){
		getline(cin,s);
		int len=s.length();
		d[0]=1;
		for(int i=1;i<len;i++){
			d[i]=d[i-1]+1;
			for(int j=i-1;j>=0;j--){
				if(check(j,i))	d[i]=min(d[i],d[j-1]+1);
			}
		}
		cout<<d[len-1]<<endl;
	}
	
} 


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39665840/article/details/79946106
个人分类: DP ACM
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭