HDU 4628(动态规划-状压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就好了 dp[i]表示到状态i的最小次数

代码如下:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<string>
#include<cstring>
#include<vector>
using namespace std;

const int inf=1e9+7;
string str;
vector<int> vec;
int dp[1<<16];
bool check(int n)
{
    vector<char > s;
    for (int i=0;i<16&&((1<<i)<=n);i++) {
        if (n&(1<<(i))) s.push_back(str[i]);
    }
    int left=0,right=s.size()-1;
    while (right>=left) {
        if (s[right]!=s[left]) return false;
        right--;
        left++;
    }
    return true;
}
void init(int n)
{
    vec.clear();
    for (int i=1;i<(1<<n);i++) {
        if (check(i)) vec.push_back(i);
    }
}
int main()
{
    int t;
    scanf("%d",&t);
    while (t--) {
        cin>>str;
        init(str.size());
        int len=str.size();
        for (int i=0;i<=((1<<len)-1);i++) {
            dp[i]=inf;
        }
        dp[0]=0;
        for (int i=0;i<=((1<<len)-1);i++) {
            if (dp[i]==inf) continue;
            for (int j=0;j<vec.size();j++) {
                if (!(i&(vec[j]))) {
                    dp[i|vec[j]]=min(dp[i|vec[j]],dp[i]+1);
                }
            }
        }
        printf("%d\n",dp[(1<<len)-1]);
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值