首页 > 代码库 > UVA 11552 Fewest Flops

UVA 11552 Fewest Flops

题解:

也是比较简单的DP

dp[i][j]表示第i个。以字母j结尾的最小值

注意小trick. 整个分组都同一个字母,这时候就不用判断头尾是否相同了

代码用到了一些c ++ 11的新姿势,auto太强了~

代码:

#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
#define se second
#define fs first
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define pii pair<int,int>
const int INF = 1000000000;
const int maxn = 10050;
const int M = 4000;

set< int > s[ 1050 ];

int T, n, k;
char str[ 1050 ];
int dp[ 1050 ][ 30 ];

int main()
{
    scanf( "%d", &T );
    while( T -- )
    {
        scanf( "%d", &k );
        scanf( "%s", str + 1 );
        int len = strlen( str + 1 );
        n = len / k;
        for( int i = 1; i <= n; i ++ ) s[ i ].clear();
        for( int i = 1; i <= n; i ++ )
        for( int j = ( i - 1 ) * k + 1; j <= i * k; j ++ )  s[ i ]. insert( str[ j ] - a );
        for( int i = 1; i <= n; i ++ )
        for( int j = 0; j < 26; j ++ ) dp[ i ][ j ] = INF;
        for( auto i : s[ 1 ] ) dp[ 1 ][ i ] = s[ 1 ].size();
        for( int i = 2 ; i <= n; i ++ )
        {
            if( s[ i ].size() == 1 )
            {
                for( auto j : s[ i ] )
                for( auto k : s[ i - 1 ] )
                {
                    if( k == j ) dp[ i ][ j ] = min( dp[ i ][ j ], dp[ i - 1 ][ k ] );
                    else         dp[ i ][ j ] = min( dp[ i ][ j ], dp[ i - 1 ][ k ] + 1 );
                }
            }
            else
            {
                for( auto p : s[ i ] )
                for( auto q : s[ i ] )
                {
                   if( p == q ) continue;
                   for( auto k : s[ i - 1 ] )
                   {
                       int siz = s[ i ].size();
                       if( q == k ) dp[ i ][ p ] = min( dp[ i ][ p ], dp[ i - 1 ][ k ] + siz - 1 );
                       else         dp[ i ][ p ] = min( dp[ i ][ p ], dp[ i - 1 ][ k ] + siz );
                   }
                }
            }
        }
        int G = INF;
        for( auto i : s[ n ] ) G = min( G, dp[ n ][ i ] );
        printf( "%d\n", G );
   }
   return 0;
}

 

UVA 11552 Fewest Flops