HDU 4628 Pieces (状压DP)

Pieces

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


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
 

 

Recommend
zhuyuanchen520
 

 

 

题意:

给定一个串,每次可以删除一个回文子串,问把全串删干净的最少次数。

思路:

用状态压缩把所有的状态枚举出来,用数组记录所表示状态所有字符被删除干净的最少次数。

状态:dp[x]表示在状态x下把所有字符删除的最少次数。

状态压缩:dp[x] = min{dp[x], dp[k]}(k是x的子集)

这样的dp的边界不再是dp[0]或dp[n]了。而是对每个状态都要设定原始值,如果某个状态是完全回文的,则dp[x] = 1,否则,dp[x] 就是一个最大值(目前子串的长度)

 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>

using namespace std;

const int N=16;
const int INF=0x3f3f3f3f;

char str[30];
int len,dp[1<<16];
vector<int> vt;

int solve(int k){
    vt.clear();
    for(int i=0;i<=len;i++)
        if(k&(1<<i))
            vt.push_back(i);
    int sz=vt.size()-1;
    for(int i=0;i<sz/2;i++)
        if(str[vt[i]]!=str[vt[sz-i]])
            return vt.size();
    return 1;
}

int main(){

    //freopen("input.txt","r",stdin);

    int t;
    scanf("%d",&t);
    while(t--){
        scanf("%s",str);
        len=strlen(str);
        for(int i=1;i<=(1<<len)-1;i++){
            dp[i]=solve(i);
            for(int j=i;j;j=(j-1)&i)
                dp[i]=min(dp[i],dp[j]+dp[j^i]);
        }
        printf("%d\n",dp[(1<<len)-1]);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值