Hdu 4628 Pieces

Pieces

                   Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)


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
 


状态压缩DP



#include<cstdio>
#include<cstring>

#define Min(a,b) (a<b?a:b)

int cnt,n;
char ch[100];
int d[1<<16];

void DFS(int tmp,int x,int y)
{
	int i,j,a;
	for(i=x+1;i<y;i++)
	{
		if(tmp&1<<i)
		{
			a=tmp^1<<i;
			d[a]=Min(d[a],d[cnt]+1);
		}
		else
			continue;
		for(j=y-1;j>i;j--)
		{
			if(ch[i]==ch[j] && tmp&1<<i && tmp&1<<j)
			{
				
				
				a=a^1<<j;
				d[a]=Min(d[a],d[cnt]+1);
				DFS(a,i,j);
				a=a^1<<j;
			}
		}
	}
}

int main()
{
	int T;
	int i,j;
	int tmp;

	scanf("%d",&T);

	while(T--)
	{
		scanf("%s",ch);
		n=strlen(ch);
		memset(d,1,sizeof(d));

		d[(1<<n)-1]=0;
		for(cnt=(1<<n)-1;cnt>0;cnt--)
		{
			if(d[cnt]>=d[0]-1)
				continue;
			for(i=0;i<n;i++)
			{
				if(cnt&1<<i)
				{
					tmp=tmp=cnt^1<<i;
					d[tmp]=Min(d[tmp],d[cnt]+1);
				}
				else
					continue;
				for(j=i+1;j<n;j++)
					if(ch[i]==ch[j] && cnt&1<<j)
					{
						tmp=tmp^1<<j;
						d[tmp]=Min(d[tmp],d[cnt]+1);
						DFS(tmp,i,j);
						tmp=tmp^1<<j;
					}					
			}
		}
		printf("%d\n",d[0]);
	}

	return 0;
}

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值