hdu 4628 每次消掉一个回文串需要的最少次数 很帅的题

Pieces

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


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
2013 Multi-University Training Contest 3

题意:
将一个长度最大为16的字符串    每次消掉一个回文串需要的最少次数      消掉的回文子串可以是不连续的 即 abcdba   我们可以消去abba  剩下cd




思路:
找出其所有回文子串对应的二进制编码 即1代表取这个字符 0代表不取       然后  DFS记忆化搜索 这些编码    具体看代码

#include<stdio.h>
#include<string.h>
char s[20],s1[20],s2[20];
int que[1<<17],cnt,len;//保存所有的回文子串
int mn[1<<17];
int canadd(int k)//当前子串是不是回文串
{
    int i,j=0;
    for(i=0;i<len;i++)
    {
        if(k&1<<i)
            s1[j++]=s[i];
    }
    s1[j]='\0';
    strcpy(s2,s1);
    strrev(s1);
    if(strcmp(s1,s2)==0) return 1;
    else return 0;
}
void find_str()//找回文字串
{
    int i,n;
    cnt=0;
    n=1<<len;
   // printf("n=%d\n",n);
    for(i=1;i<n;i++)///
    {
        //printf("i1=%d\n",i);
        if(canadd(i))
        {
          //  printf("i2=%d\n",i);
            //printf("%d\n",i);
            que[cnt++]=i;
        }
    }
}
int DFS(int k)
{
    int i,mmin=99999999;
    if(mn[k]!=-1) return mn[k];
    if(k==(1<<len)-1) return 0;

    for(i=0;i<cnt;i++)
     {
         if(que[i]&k) continue;//如果2者没有2个对应位同时为1 说明他们可以合并成一个串 去递归这个串
         int num=DFS(que[i]|k)+1;
         if(mmin>num) mmin=num;
     }
     mn[k]=mmin;
     return mn[k];
}
int main()
{
    int cas;

    scanf("%d",&cas);
    while(cas--)
    {
        memset(mn,-1,sizeof(mn));
        scanf("%s",s);
        len=strlen(s);
        find_str();

        int ans=DFS(0);
        printf("%d\n",ans);
    }

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值