[HDU4628]解题报告,状态压缩dp

每天一篇结题报告计划(2/∞)

今天要讲的是一篇很有意思的状压dp,数学课一直在想这题,然后一节课没听emmm。

Pieces

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 asfew 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

这道题一开始想的广搜然后想想复杂度就瑟瑟发抖了
然后开始考虑状态压缩
用二进制来表示一个数是否已经删去,1为删去,0为未删
dp[s]表示在s(转化为二进制)的情况下,最少需要几步
为了节省时间,我们做一次预处理,把所有回文子序列记录下来,并把对应的dp[s]改成1(回文子系列只用一次就能完成)
我们的目标是从0变成1111.....
字符串长度为len的话
我们要的目标状态就是1<<len-1(位运算)
如长度为4,目标为10000-1=1111
遍历0到1<<len-1,把这个状态和预处理出来的状态合并,得到新的状态,新状态的步数就等于原状态+1
那我就放代码了
#include<iostream>
#include<cstring>
using namespace std;
string str;
int len,dp[65537],cycle[65537],tot;//cycle是处理出来的回文子序列,tot记录个数
bool cle(int x)//判断x状态是否为回文
{  
    if(x==0)
    {
    	return true; 
	}
    int i=0,j=len-1;  
    while(i<j)
	{  
        while((x&(1<<i))==0)//找到子状态最左边的1
        	i++;
        	
        while((x&(1<<j))==0)//找到子状态最右边的1
        	j--;
        if(str[i]!=str[j])
			return false;  
		i++;
		j--;  
    }  
    return true;  
}  
int main()
{

	int N;
	cin>>N;
	while(N--)
	{
		tot=0;
		memset(dp,0x3F,sizeof(dp));
		//dp[0]=0;
		cin>>str;
		len=str.length();
		int maxx=(1<<len)-1;
		for(int i=1;i<=maxx;i++)
		{
			if(cle(i))
			{
				dp[i]=1;
				cycle[++tot]=i;
			}
		}
		//cout<<tot<<endl;
		for(int i=1;i<=maxx;i++)
		{
			for(int j=1;j<=tot;j++)
			{
				if((i&cycle[j])==0)
				{
					dp[i|cycle[j]]=min(dp[i|cycle[j]],dp[i]+1);//要判断在i的位上是否已有1存在
				}
			}
		}
		cout<<dp[maxx]<<endl;
	}
}









原文地址:https://www.cnblogs.com/sherrlock/p/9525798.html