HDU4628+状态压缩DP
/* 状态压缩DP 题意:每次可以去掉一个回文串,求最少几步能取完。 */ #include<stdio.h> #include<string.h> #include<stdlib.h> #include<algorithm> #include<iostream> #include<queue> #include<map> #include<math.h> using namespace std; typedef long long ll; //typedef __int64 int64; const int maxn = 18; const int inf = 0x3f3f3f3f; const double pi=acos(-1.0); const double eps = 1e-8; int dp[ 1<<maxn ]; char s[ maxn ]; int state[ 1<<maxn ];//回文的状态 bool JudgeOneZero( int ss,int len ){ int Index[ maxn ]; int cc = 0; int IndexOfString = 0; while( IndexOfString<len ){ if( ss%2==1 ){// 所有的 “1” 代表该位置上有字母,即这些组合是回文串 Index[ cc++ ] = IndexOfString; } ss /= 2; IndexOfString++; } if( cc==1 ) return true; int L,R; L = 0; R = cc-1; while( L<=R ){ if( s[Index[L]]!=s[Index[R]] ) return false; L++; R--; } return true; } int init_state( int len ){ int cnt = 0; int N = 1<<len; state[ cnt++ ] = 0; for( int i=1;i<N;i++ ){ if( JudgeOneZero( i,len )==true ){ state[ cnt++ ] = i; } } return cnt; } //初始化 bool Judge( int cur,int nxt,int len ){//当前状态cur,前一状态nxt int Index[ maxn ]; int cc = 0; int IndexOfString = 0; while( IndexOfString<len ){ if( cur%2==1 ){ if( nxt%2==0 ) return false; }//当前状态为1,前一状态必须为1 if( nxt%2==0 ){ if( cur%2==1 ) return false; }//前一状态是0,当前状态也必须是0 if( cur%2==0&&nxt%2==1 ){ Index[ cc++ ] = IndexOfString; } IndexOfString++; cur /= 2; nxt /= 2; } if( cc==1 ) return true; int L,R; L = 0; R = cc-1; //printf("cc=%d\n",cc); while( L<=R ){ if( s[Index[L]]!=s[Index[R]] ) return false; L++; R--; } return true; } int main(){ int T; scanf("%d",&T); while( T-- ){ scanf("%s",s); int n = strlen(s); int cnt = init_state( n ); int N = (1<<n); for( int i=0;i<N;i++ ) dp[ i ] = inf; dp[ N-1 ] = 0; /* for( int i=N-2;i>=0;i-- ){ for( int j=0;j<N;j++ ){ if( i==j ) continue; if( Judge( i,j,n )==true ){ //printf("i=%d, j=%d\n",i,j); dp[ i ] = min( dp[i],dp[j]+1 ); //printf("dp[%d] = %d\n\n",i,dp[i]); } } } */ for( int i=N-2;i>=0;i-- ){ for( int j=0;j<cnt;j++ ){ if( 0==(i&state[j]) ){ dp[ i ] = min( dp[i],dp[state[j]|i]+1 ); } } } printf("%d\n",dp[0]); } return 0; }
补充:软件开发 , C++ ,