HDU4628——Pieces

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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容