hdu4628 Pieces
题目大意
给你一个字符串 s s s,每次操作可以消除 s s s的一个子串(可以不连续),但是这个字串必须是回文的,请你求出最少用几次可以把该字符串清空
例:字符串 a x b y c z b e a axbyczbea axbyczbea,第一次可以删除 a b c b a abcba abcba变成 x y z e xyze xyze
剩下 4 4 4次每次删除一个字母
所以最少用 5 5 5次就可以把该字符串清空
输入格式
第一行一个正整数 t , t ≤ 10 t,t \leq 10 t,t≤10
接下来输入 t t t行,每行一个长度不超过 16 16 16的字符串 s s s
输出格式
对于每个字符串 s s s,输出一行正整数,表示最少需要多少次就能把字符串清空
输入样例
2
aa
abb
输出样例
1
2
思路
一看字符串的长度 ≤ 16 \leq 16 ≤16就可以状态压缩
令一个 01 01 01二进制数表示
0 0 0 不选该位, 1 1 1选该位构成的字串是不是回文的
所以我们可以先把所有回文的字串通过 c h e c k check check函数预处理出来
再用 a a a数组存下来所有的回文字串
接下来我们就可以进行 d p dp dp了
由于 d p dp dp的舒徐不是很好确定
所以我们可以使用记忆化搜索(本质还是 d p dp dp)
每次的 d f s ( x ) dfs(x) dfs(x)表示当前要求的状态是 x x x
具体细节见代码
(由于是多组数据,所以一定不要忘记初始化)
代码实现
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
inline int read()
{
int r,s=0,c;
for(;!isdigit(c=getchar());s=c);
for(r=c^48;isdigit(c=getchar());(r*=10)+=c^48);
return s^45?r:-r;
}
const int N=20,VAL=1100000;//1048576
int t,l,maxn,cnt;
char s[N];
int a[VAL];
inline bool check(int x)//判断二进制所代表的字串是否为回文的
{
int f=1,e=l;
while((f<e)&&(f<=l)&&(e>=1))
{
while(!(((1<<(l-f))&x))&&(f<=l)) f++;
while(!(((1<<(l-e))&x))&&(e>=1)) e--;
if(s[f]!=s[e])return 0;
f++,e--;
}
return 1;
}
int dp[VAL],inf;
int dfs(int x)//记忆化搜索
{
int &ans=dp[x];//这样修改ans的值的时候dp[x]的也就同时修改了
if(ans!=inf)return ans;
for(int i=1;i<=cnt;i++)
{
if(a[i]>x)break;
if(((x^maxn)&a[i]))continue;
ans=min(ans,dfs(x^a[i]));
}
ans++;
return ans;
}
int main()
{
t=read();
while(t--)
{
memset(dp,0x3f3f,sizeof(dp));//初始化
inf=dp[1];
scanf("%s",s+1);
l=strlen(s+1);
maxn=(1<<l)-1;
cnt=0;
for(int i=1;i<=maxn;i++)
if(check(i))
a[++cnt]=i,dp[i]=1;
printf("%d\n",dfs(maxn));
}
return 0;
}