hdu 4628 Pieces 状态压缩dp

Pieces

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

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
 
 
这一题的对字符串的回文判断是可以想到的。
关键在于如果更新它,这里有技巧。
看了别人的题解 ,过的这道题。当时觉得没有思路,现在返回去看。
有一个地方是很值得学习的。
思路:
   1.预处理,求出输入的串的子串中,那些满足回文情况。
   2.更新,dp[1<<k]。

  for(i=1;i<k;i++)//枚举每一种情况。
  {
     for(j=i;j>=1;j--)//对于每一种情况,首选就是它自身了。
    {
      if(flag[j])//判断是否为回文情况
         {
         if(dp[i-j]+1<dp[i])
         dp[i]=dp[i-j]+1;//更新
         }
       j=i&j;//这句很重要
    }
  }

 
 #include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std; char a[];
int dp[<<];
bool flag[<<];
void solve(int n)
{
int i,j,k,ans,len;
int f[];
k=<<n;
for(i=;i<k;i++)//预处理
{
ans=;
for(j=;j<=;j++)
if( (i&(<<j))>)
f[++ans]=j;
len=ans/; for(j=;j<=len;j++)
if( a[f[j]]!=a[f[ans-j+]]) break;
if(j>len) flag[i]=true;
else flag[i]=false;
}
for(i=;i<k;i++)
dp[i]=;
dp[]=;
for(i=;i<k;i++)
{
for(j=i;j>=;j--)
{
if(flag[j])
{
if(dp[i-j]+<dp[i])
dp[i]=dp[i-j]+;
}
j=i&j;
}
}
printf("%d\n",dp[k-]);
}
int main()
{
int T,n;
while(scanf("%d",&T)>)
{
while(T--)
{
scanf("%s",a);
n=strlen(a);
solve(n);
}
}
return ;
}
上一篇:HDU 3001(状态压缩dp)


下一篇:HDU 2167 Pebbles 状态压缩dp