Pieces
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 1390 Accepted Submission(s): 708
Problem Description
You heart broke into pieces.My string broke into pieces.But you will recover one day,and my string will never go back.
Given a string s.We can erase a subsequence of it if this subsequence is palindrome in one step. We should take as few steps as possible to erase the whole sequence.How many steps do we need?
For example, we can erase abcba from axbyczbea and get xyze in one step.
Input
The first line contains integer T,denote the number of the test cases. Then T lines follows,each line contains the string s (1<= length of s <= 16).
T<=10.
Output
For each test cases,print the answer in a line.
Sample Input
2
aa
abb
Sample Output
1
2
Source
2013 Multi-University Training Contest 3
Recommend
zhuyuanchen520
1 //1109MS 488K 920 B C++ 2 /* 3 4 题意: 5 在一个串中以最少步骤中剔出全部回文子串 6 7 状态压缩: 8 dp[i]表示道歉状态下剔出的最少次数 9 先用状态压缩求出每个状态是否为回文串, 10 再使用背包思想解出最优解 11 12 */ 13 #include<stdio.h> 14 #include<string.h> 15 #define inf 0x7ffffff 16 int dp[1<<18]; 17 char c[20],tc[20]; 18 int len; 19 int Min(int a,int b) 20 { 21 return a<b?a:b; 22 } 23 void init() //初始化,判断dp[i]是否为回文串 24 { 25 for(int i=0;i<(1<<len);i++) 26 dp[i]=inf; 27 for(int i=1;i<(1<<len);i++){ //枚举所有状态 28 int num=0; 29 int flag=1; 30 for(int j=0;j<len;j++){ 31 if(i&(1<<j)) tc[num++]=c[j]; 32 } 33 tc[num]='\0'; 34 for(int j=0;j<num;j++){ 35 if(tc[j]!=tc[num-j-1]){ 36 flag=0;break; 37 } 38 } 39 if(flag) dp[i]=1; 40 } 41 } 42 int main(void) 43 { 44 int t; 45 scanf("%d",&t); 46 while(t--) 47 { 48 scanf("%s",c); 49 len=strlen(c); 50 init(); 51 for(int i=1;i<(1<<len);i++){ 52 for(int j=i;j>0;j=i&(j-1)){ //j=i&(j-1)跳到下一状态 53 dp[i]=Min(dp[i],dp[i^j]+dp[j]); 54 } 55 } 56 printf("%d\n",dp[(1<<len)-1]); 57 } 58 return 0; 59 }