HDU - 4628:Pieces(状压DP)

xiaoxiao2021-02-28  52

Pieces

                                                         Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)                                                                                 Total Submission(s): 2261    Accepted Submission(s): 1201 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

思路:状压DP。用d[i]表示删除状态为i的字符串的删除次数。先处理出所有回文子串使其d[i]=1。并用tp[MAX]保存下来。再来循环(1<<n)*MAX次。

#include<bits/stdc++.h> using namespace std; char s[20]; int d[1<<16],n,tp[1<<16],MAX; bool check(int x) //判断状态为i的字符串是不是回文的 { string a=""; for(int i=0;i<n;i++,x/=2)if(x%2)a+=s[i]; for(int i=0,j=a.size()-1;j>=i;i++,j--)if(a[i]!=a[j])return 0; return 1; } int main() { int T;cin>>T; while(T--) { scanf("%s",s); n=strlen(s); memset(d,0x3f3f3f3f,sizeof d); MAX=0; d[0]=0; tp[MAX++]=0; for(int i=1;i<(1<<n);i++)if(check(i))d[i]=1,tp[MAX++]=i; for(int i=0;i<(1<<n);i++) { for(int j=0;j<MAX;j++) { if(i&tp[j])continue; d[i|tp[j]]=min(d[i|tp[j]],d[i]+d[tp[j]]); } } cout<<d[(1<<n)-1]<<endl; } return 0; }

转载请注明原文地址: https://www.6miu.com/read-35910.html

最新回复(0)