zoukankan      html  css  js  c++  java
  • hdu 4628 Pieces(状态压缩+记忆化搜索)

    Pieces

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


    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
     

    Author
    WJMZBMR
     

    Source
    题意:给一个字符串,长度<=16,每次去掉一个回文串。能够中不连续的。问最少用多少次把所给的串都去掉。
    解题:先用状态压缩把回文串的状态标记。再用记忆化搜索或dp。
    #include<stdio.h>
    #include<string.h>
    const int inf=20;
    int dp[1<<17],len,flag[1<<17];
    char str[20];
    bool judge(int sta){
        char s[20];
        int k=0 , l , r;
        for(int i=0; (1<<i)<=sta; i++)
            if((1<<i)&sta)
            s[k++]=str[i];
        if(k==0)return 0;
        if(k==1)return 1;
        if(k&1){
            l=k/2-1; r=l+2;
        }
        else{
            l=k/2-1; r=l+1;
        }
        while(r<k&&s[l]==s[r])l--,r++;
        if(r<k)return 0;
        else return 1;
    }
    void dfs(int sta){
        if(dp[sta]!=inf)
            return ;
        for(int s=sta-1;s>0; s=(s-1)&sta){
            if(!flag[s^sta])continue;
            dfs(s);
            if(dp[sta]>dp[s]+1)
                dp[sta]=dp[s]+1;
        }
        if(judge(sta))
            if(dp[sta]>1)
                dp[sta]=1;
    }
    int main()
    {
        int T;
        scanf("%d",&T);
        while(T--){
            scanf("%s",str);
            len=strlen(str);
            for(int i=(1<<len)-1; i>0; i--){
                dp[i]=inf;
                flag[i]=judge(i);
            }
            dp[0]=0;flag[0]=0;
    
            dfs((1<<len)-1);
            printf("%d
    ",dp[(1<<len)-1]);
        }
        return 0;
    }
    


     
  • 相关阅读:
    JS模板引擎 :ArtTemplate (2)
    JS模板引擎 :ArtTemplate (1)
    nodeJs 初探 ~
    javascript高级函数
    Js高程笔记->引用类型
    html5离线存储
    (摘抄)HTTP 协议详解
    cordova /phonegap 自定义插件
    phonegap/cordova常用命令
    phonegap上传以及下载图片
  • 原文地址:https://www.cnblogs.com/llguanli/p/7010523.html
Copyright © 2011-2022 走看看