美文网首页
HDU4628——Pieces

HDU4628——Pieces

作者: xz闲语岁月 | 来源:发表于2017-08-23 22:15 被阅读0次

    Problem

    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


    思路

    题意为给定字符串,长度<=16,每次去掉一个回文串,问最少用多少次把所给的串都去掉。
    先用状态压缩把回文串的状态标记,再用dp。

    代码

    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    using namespace std;
    bool dp[1<<16];
    int res[1<<16];
    char str[20];
    int main(){
       int t,n;
       scanf("%d",&t);
       while(t--){
           scanf("%s",str);
           n=strlen(str);
           dp[0]=false;
           for(int i=1;i<(1<<n);i++){
               int l=0,r=n-1;
               bool flag=true;
               while(l<=r){
                   while(l<n&&(i&(1<<l))==0)l++;
                   while(r>=0&&(i&(1<<r))==0)r--;
                   if(l>r)break;
                   if(str[l]!=str[r]){flag=false;break;}
                   l++;
                   r--;
               }
               dp[i]=flag;
               res[i]=n;
           }
           res[0]=0;
           for(int i=1;i<(1<<n);i++){
               for(int j=i;j;j=(i&(j-1))){
                   if(dp[j])res[i]=min(res[i],res[i-j]+1);
               }
           }
           printf("%d\n",res[(1<<n)-1]);
       }
       return 0;
    }
    

    相关文章

      网友评论

          本文标题:HDU4628——Pieces

          本文链接:https://www.haomeiwen.com/subject/kngjdxtx.html