ACM篇:POJ 1753----Flip Game

很早的題,今天終於AC了。

分黑白兩種情況枚舉第一行,與Fliptile類似。

#include <iostream>
#include <cstdio>
#include <cstring>

#define min(a,b) (((a) < (b)) ? (a) : (b))
using namespace std;
const int MAX = 4;
const int SUP = 16;
bool board[MAX+2][MAX+2];
bool temp_board[MAX+2][MAX+2];
int ans;
int step;
char readchar()
{
    char t;
    while (t = getchar())
    {
        if (t == 'b' || t == 'w')
            return t;
    }
}

void read_board()
{
    for (int i = 1; i <= MAX; i++)
        for (int j = 1; j <= MAX; j++)
            board[i][j] = (readchar() == 'b') ? 1 : 0;
}

const int ROW[] = {0, 0, 0, 1, -1};
const int COL[] = {0, 1, -1, 0, 0};
void _flip(int r, int c)
{
    for (int i = 0; i < 5; i++)
        temp_board[r+ROW[i]][c+COL[i]] = !temp_board[r+ROW[i]][c+COL[i]];
}
void _operate(int ord, int aim)
{
    for (int j = 1; j <= MAX; j++)
    {
        if (ord & 1)
        {
            _flip(1, j);
            step++; 
        }
        ord >>= 1;
    }

    for (int i = 2; i <= MAX; i++)
        for (int j = 1; j <= MAX; j++)
        {
            if (temp_board[i-1][j] != aim)
            {
                _flip(i, j);
                step++;
            }
        }
}

bool is_ok(int aim)             // all zeros or not
{
    for (int j = 1; j <= MAX; j++)
        if (temp_board[MAX][j] != aim)
            return false;           
    return true;
}
int main()
{
    //  input
    read_board();

    //  enumberate
    ans = SUP;
    for (int aim = 0; aim <= 1; aim++)
    {   
        int sz = 1 << MAX;
        for (int i = 0; i < sz; i++)
        {
            step = 0;
            memcpy(temp_board, board, sizeof(board));

            _operate(i, aim);
            if (is_ok(aim))
                ans = min(ans, step);
        }
    }
    if (ans != SUP)
        printf("%d", ans);
    else 
        printf("Impossible");
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章