现在的位置: 首页 > 综合 > 正文

Hdu 4628 Pieces

2018年01月14日 ⁄ 综合 ⁄ 共 1426字 ⁄ 字号 评论关闭

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;
}

 

抱歉!评论已关闭.