HDU 4628 Pieces

Pieces

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


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

每个子序列相当于一个数字。 在根据数字还原该子序列。 并标记是否是回文串。
最后背包下。

j &= i 表示的是直接跳到下一个子序列, 减去大量多余的判断。
例如: ABCDEFGH
对于GH, 的子序列只有  GH, G, H。
但是 GH对应的数字是 11000000 = 192. 
H对应的是  10000000 = 128.  =  10111111 (j)  & 11000000 (i) 
G对应的是  01000000 =  64    =   01111111 (j) & 11000000 (i) 
空串 00000000 = 0 = 00111111 & 11000000 结束j循环。

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

//状态压缩 + 背包

const int v = 100000 + 50;
int T, dp[1 << 16];
char ch[20];
bool is_ok[1 << 16];
int main() {
    int i, j;
    scanf("%d", &T);
    while(T--) {
        scanf("%s", &ch);
        memset(is_ok, false, sizeof(is_ok));
        int len = strlen(ch);
        for(i = 1; i < (1 << len); ++i) {
            int v[20], top = 0;
            for(j = 0; j < len; ++j)
                if(i & (1 << j))
                    v[top++] = j;
            for(j = 0; j <= top / 2; ++j)
                if(ch[v[j]] != ch[v[top - 1 - j]])
                    break;
            if(j > top / 2)
                is_ok[i] = true;
        }
        for(i = 1; i < (1 << len); ++i)
            dp[i] = 16;
        dp[0] = 0;
        for(i = 1; i < (1 << len); ++i)
            for(j = i; j >= 1; --j) {
                if(is_ok[j])
                    dp[i] = min(dp[i], dp[i - j] + 1);
                j &= i;
            }
        printf("%d\n", dp[(1 << len) - 1]);
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值