Partitioning by Palindromes(UVa-11584) :
问题描述
题目简述
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 ofcharacters is a list of one ormore disjoint non-empty groups of consecutive characters whose concatenation 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 partition of these characters suchthat each group in the partitionis 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?
输入/输出格式
输入格式:
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.
样例
输入样例:
3
racecar
fastcar
aaadbccb
输出样例:
1
7
3
问题分析
解题思路
直接设dp(i,j)为子串str(i,j)可以分成的最少的回文串数量。那么dp(i,j)=min(dp(i,j),dp(i,k)+1)(如果str(k+1,j)为回文串)。然后需要预先处理字符串,先将字符串中的回文子串求出(注意递归的时候需要记忆化搜索,否则会报T),之后写出dp,最后答案为dp(0,n-1)。
参考代码
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
const int inf=100100;
int s[1010][1010];
string str;
int dp[1010];
int n;
void init()
{
memset(s,0,sizeof(s));
memset(dp,inf,sizeof(dp));
str.clear();
}
int ispali(int i,int j)
{
//printf("get message str[%d],str[%d]:(%c,%c)\n",i,j,str[i],str[j]);
if(s[i][j]==1) return s[i][j];
if(i>j) return 1;
if(str[i]==str[j])
{
s[i][j]=ispali(i+1,j-1);
//printf("s[%d][%d]=%d\n",i,j,s[i][j]);
return s[i][j];
}
else return 0;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
init();
cin>>str;
for(int j=0;j<str.length();j++)
{
for(int k=j;k<str.length();k++)
{
ispali(j,k);
}
}
dp[0]=1;
for(int j=1;j<str.length();j++)
{
if(s[0][j]==1) dp[j]=1;
for(int k=1;k<=j;k++)
{
if(s[k][j]==1) dp[j]=min(dp[j],dp[k-1]+1);
}
}
printf("%d\n",dp[str.length()-1]);
}
return 0;
}
心得体会
怎么说呢,这几天练的dp,却还是没有什么太大的感觉,想这些东西还是有些不顺利,还是要多练吧,之前做题实在太少了。