D - Palindrome Partitioning

本文介绍了一种使用动态规划解决字符串最小回文分割问题的方法。通过一维数组记录从每个字符开始到当前位置的最少回文子串数量,最终求得整个字符串的最小分割数。

这题我用了很笨的方法,可是经过一番努力我还是搞定了,很激动很激动

用一维数组记录从第一个字符到该位置最少回文串个数

Description

A palindrome partition is the partitioning of a string such that each separate substring is a palindrome.

For example, the string "ABACABA" could be partitioned in several different ways, such as {"A","B","A","C","A","B","A"}, {"A","BACAB","A"}, {"ABA","C","ABA"}, or {"ABACABA"}, among others.

You are given a string s. Return the minimum possible number of substrings in a palindrome partition of s.

Input

Input starts with an integer T (≤ 40), denoting the number of test cases.

Each case begins with a non-empty string s of uppercase letters with length no more than 1000.

Output

For each case of input you have to print the case number and the desired result.

Sample Input

3

AAAA

ABCDEFGH

QWERTYTREWQWERT

Sample Output

Case 1: 1

Case 2: 8

Case 3: 5

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
char a[1010];
int dp[1010];
int main()
{
	int n,r,m,ca=1;
	scanf("%d",&r);
	while(r--)
	{
		scanf("%s",a+1);
        n=strlen(a+1);
        for(int i=1;i<=n;i++)
				dp[i]=i; 
							
			m=n;	 
			int i,j,k,s,t; 
			for( i=1;i<n;i++)
			{	
				int x,sum;
				if(a[i]==a[i+1])
				{
					sum=0;x=i;
					for(j=i,k=i+1;j>=1,k<=n;j--,k++)
					{
						if(a[j]!=a[k] )
							break;
						if(a[j]==a[i] && a[k]==a[i]) sum+=2;
					}
					s=j+1;t=k-1;  
					dp[t]=min(dp[t],dp[s-1]+1);	          
					if(dp[t]==dp[s-1]+1)
					{
						if(sum==t-s+1)
							for(int l=s+1;l<=t;l++)
								dp[l]=dp[s];     	 
							else 
								for(int l=i+1;l<=t;l++)
								{
									dp[l]=dp[x-1]+1;
									x--; 
								}
								for(int l=t+1;l<=n;l++)
									dp[l]=dp[t]+l-t;		   
					}	            	            	            
				}         			
				if(a[i-1]==a[i+1] && i>=2)
				{
					sum=1;x=i-1;
					for(j=i-1,k=i+1;j>=1,k<=n;j--,k++)
					{
						if(a[j]!=a[k] )
							break;
						if(a[j]==a[i] && a[k]==a[i]) sum+=2;
					} 
					s=j+1;t=k-1;  
					dp[t]=min(dp[t],dp[s-1]+1);
					
					if(dp[t]==dp[s-1]+1)
					{
						if(sum==t-s+1)
							for(int l=s+1;l<=t;l++)
								dp[l]=dp[s];    
							else 
								for(int l=i+1;l<=t;l++)
								{
									dp[l]=dp[x-1]+1;       			
									x--; 
								}
								for(int l=t+1;l<=n;l++)
									dp[l]=dp[t]+l-t;		   
					}					      		      					 			 	 
				}
			}   
			printf("Case %d: %d\n",ca++,dp[n]);
	}	
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值