D - Palindrome Partitioning

来源:互联网 发布:抓包8888端口干嘛的 编辑:程序博客网 时间:2024/06/04 20:02

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

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

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]);}}


原创粉丝点击