Pieces(状压dp+字符串回文处理)

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

把回文串先预处理标记出来,再状压dp

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define inf 0x3f3f3f3f
char s[20];
int dp[(1<<16)+5],sign[(1<<16)+5];
int judge(int x)
{
    int l,r,len;
    len=strlen(s);
    l=0;
    r=len-1;
    while(l<r)
    {
        while(!(x&(1<<l)))
        l++;
        while(!(x&(1<<r)))
        r--;
        if(s[l]!=s[r])
        return 0;
        l++;
        r--;
    }
    return 1;
}
int main()
{
    int t,i,j,len;
    scanf("%d",&t);

    while(t--)
    {
        cin>>s;
        len=strlen(s);
        memset(dp,inf,sizeof(dp));
        memset(sign,0,sizeof(sign));
        dp[0]=0;
        for(i=1;i<(1<<len);i++)
        if(judge(i))
        sign[i]=1;
        for(i=1;i<(1<<len);i++)
        {
            for(j=i;j>0;j=i&(j-1))
            {
                if(sign[j])
                dp[i]=min(dp[i],dp[i-j]+1);
            }
        }
        printf("%d\n",dp[(1<<len)-1]);

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sdauguanweihong/article/details/82939562