首页 > 代码库 > CEOI 2002, POJ 1038 Bugs Integrated, Inc. 状态压缩 DP

CEOI 2002, POJ 1038 Bugs Integrated, Inc. 状态压缩 DP

有点点小虐心。


#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;

const int ternarys[12] = { 0, 1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049 };
int DP[2][59049];
int bit_map[155][15];
int pre_line[15];
int now_line[15];

int N, M, K;


int transform_to_decimal( int* arr ){

    int res = 0;
    for( int m = 1; m <= M; ++m )
        res += arr[m] * ternarys[m];
    return res;

}


void transform_to_ternary( int val, int* arr ){
    for( int m = 1; m <= M; ++m ){
        arr[m] = val % 3;
        val /= 3;
    }
}


void dfs_search( int n, int m, int last, int state ){

    DP[n % 2][state] = max( DP[n % 2][state], last );

    if( m >= M )
        return;

    if( !pre_line[m] && !pre_line[m + 1] && !now_line[m] && !now_line[m + 1] ){
        now_line[m] = now_line[m + 1] = 2;
        int _state = transform_to_decimal( now_line );
        dfs_search( n, m + 2, last + 1, _state );
        now_line[m] = now_line[m + 1] = 0;
    }

    if( m < M - 1 && !now_line[m] && !now_line[m + 1] && !now_line[m + 2] ){
        now_line[m] = now_line[m + 1] = now_line[m + 2] = 2;
        int _state = transform_to_decimal( now_line );
        dfs_search( n, m + 3, last + 1, _state );
        now_line[m] = now_line[m + 1] = now_line[m + 2] = 0;
    }

    dfs_search( n, m + 1, last, state );

}


int main(){

    int cases;
    cin >> cases;

    while( cases-- ){

        cin >> N >> M >> K;

        for( int i = 0; i < ternarys[M + 1]; ++i )
            DP[1][i] = -1;

        memset( bit_map, 0, sizeof( bit_map ) );

        for( int k = 0; k < K; ++k ){
            int n, m;
            cin >> n >> m;
            bit_map[n][m] = 1;
        }

        for( int i = 1; i <= M; ++i )
            pre_line[i] = bit_map[1][i] + 1;

        int state = transform_to_decimal( pre_line );
        DP[1][state] = 0;

        for( int n = 2; n <= N; ++n ){

            for( int _state = 0; _state < ternarys[M + 1]; ++_state )
                DP[n % 2][_state] = -1;

            for( int _state = 0; _state < ternarys[M + 1]; ++_state ){

                if( DP[( n + 1 ) % 2][_state] == -1 )
                    continue;

                transform_to_ternary( _state, pre_line );

                for( int m = 1; m <= M; ++m ){
                    if( bit_map[n][m] )
                        now_line[m] = 2;
                    else
                        now_line[m] = max( pre_line[m] - 1, 0 );
                }

                int now_state = transform_to_decimal( now_line );

                dfs_search( n, 1, DP[( n + 1 ) % 2][_state], now_state );

            }
        }

        int res = 0;

        for( int _state = 0; _state < ternarys[M + 1]; ++_state )
            res = max( res, DP[N % 2][_state] );

        cout << res << endl;

    }

    return 0;

}


CEOI 2002, POJ 1038 Bugs Integrated, Inc. 状态压缩 DP