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,每次去掉一個回文串,問最少用多少次把所給的串都去掉枕磁。
先用狀態(tài)壓縮把回文串的狀態(tài)標(biāo)記伯顶,再用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;
}