Pieces
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 734 Accepted Submission(s): 437
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.
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.
T<=10.
Output
For each test cases,print the answer in a line.
Sample Input
2 aa abb
Sample Output
1 2
Source
Recommend
zhuyuanchen520
/**
就算是简单题,我都感觉做不出来……不会表示状态,那就什么都做不出来……
**/
#include<iostream>
#include<vector>
#include<cstdio>
#include<cstring>
using namespace std;
#define maxn 16
char s[25];
int len =0;
int all=0; //all state
int dp[1<<maxn+1];
int init(int x) /**判断某个状态对应的字符串的回文串的大小,如果字符串全部回文,返回1,否则返回字符串的长度**/
{
int st[maxn+1]= {0},f=0; //stack first *p
/**用栈来储存x状态时,每一个存在的字符所对应的位置**/
for(int i=0; i<=len; i++)
if(x&(1<<i))
st[f++]=i;
f--;
for(int j=0; j<f/2; j++) /**从中点向两边看,是否回文,如果发现不回文的任意两个个字母,就返回状态x的字符串长度**/
if(s[st[j]]!=s[st[f-j]])
return f+1;
return 1;
}
/**表示状态,实际上就是用01串来表示原来字符串每个字符是否被删掉,0对应的是被删掉的,1表示留下的**/
void DP()
{
len=strlen(s);
all=1<<len;
/**初始的状态是11111……111,就是全部都存在**/
all--;
//cout<<all<<endl;
for(int i=1; i<=all; i++) /**枚举各种状态,对其进行初始化**/
{
dp[i]=init(i); /**对每一个dp状态初始化**/
//cout<<i<<" "<<dp[i]<<endl;
for(int s0=i; s0>0; s0=(s0-1)&i) /**枚举每一个状态的子状态,
dp[状态i]=min(dp[状态i],dp[子状态s0]+dp[子状态相对与状态i的补集s0^i]),二进制和位运算的灵活运用**/
dp[i]=min(dp[i],dp[s0]+dp[s0^i]);
}
}
void print()
{
printf("%d\n",dp[all]);
}
void read()
{
int n;
cin>>n;
while(n--)
{
memset(dp,0,sizeof(dp));
cin>>s;
DP();
print();
}
}
int main()
{
read();
return 0;
}