hdu4628 Pieces

Pieces

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 366    Accepted Submission(s): 200


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




简单状态dp,先预处理一下所有回文子序列,之后就是dp了。

#include <stdio.h>
#include <map>
#include <string.h>
#include <algorithm>
using namespace std;

int dp[(1<<16)+5];
int vis[(1<<16)+5];
char str[20];

int main()
{
    int i,j,n,T,p,q;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%s",str);
        n=strlen(str);
        memset(vis,0,sizeof(vis));
        for (i=1;i<(1<<n);i++)
        {
            p=0;
            q=n-1;
            while(p<q)
            {
                while((i & (1<<p))==0 && p<n-1) p++;
                while((i & (1<<q))==0 && q>0) q--;
              //  printf("%d~~%d\n",p,q);
                if (str[p]!=str[q]) break;
                p++;q--;
            }
            if (p<q) continue;
            vis[i]=1;
         //   printf("%d!\n",i);
        }

        for (i=0;i<(1<<n);i++)
        {
            dp[i]=1000;
        }
        dp[(1<<n)-1]=0;
        for (i=(1<<n)-2;i>=0;i--)
        {
            for (j=i;j<(1<<n);j=((j+1)|i))
            {
             //   printf("%d\n",~i&j);
                if (vis[(~i) & j]) dp[i]=min(dp[j]+1,dp[i]);
            }
         //   printf("%d %d\n",i,dp[i]);
        }
        printf("%d\n",dp[0]);
    }
    return 0;
}


你可能感兴趣的:(hdu4628 Pieces)