POJ 1753 Flip Game

来源:互联网 发布:使用另一个php的变量 编辑:程序博客网 时间:2024/06/05 14:36
Flip Game
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 41203 Accepted: 17892

Description

Flip game is played on a rectangular 4x4 field with two-sided pieces placed on each of its 16 squares. One side of each piece is white and the other one is black and each piece is lying either it's black or white side up. Each round you flip 3 to 5 pieces, thus changing the color of their upper side from black to white and vice versa. The pieces to be flipped are chosen every round according to the following rules:
  1. Choose any one of the 16 pieces.
  2. Flip the chosen piece and also all adjacent pieces to the left, to the right, to the top, and to the bottom of the chosen piece (if there are any).

Consider the following position as an example:

bwbw
wwww
bbwb
bwwb
Here "b" denotes pieces lying their black side up and "w" denotes pieces lying their white side up. If we choose to flip the 1st piece from the 3rd row (this choice is shown at the picture), then the field will become:

bwbw
bwww
wwwb
wwwb
The goal of the game is to flip either all pieces white side up or all pieces black side up. You are to write a program that will search for the minimum number of rounds needed to achieve this goal.

Input

The input consists of 4 lines with 4 characters "w" or "b" each that denote game field position.

Output

Write to the output file a single integer number - the minimum number of rounds needed to achieve the goal of the game from the given position. If the goal is initially achieved, then write 0. If it's impossible to achieve the goal, then write the word "Impossible" (without quotes).

Sample Input

bwwbbbwbbwwbbwww

Sample Output

4

状态压缩+BFS,暴力枚举每种情况,题目不难,但还是参考了题解,是个不错的练习。代码如下:

#include<iostream>
using namespace std;
int rear=0,top=0;
int step[65536]={0},qstate[65536]={0};
bool r[65536]={0};

void init()
{
    int temp=0;
    char a[10];
    for(int i=0;i<4;++i)
    {
        cin>>a;
        for(int j=0;j<4;++j)
        { if(a[j]=='b') temp|=(1<<(i*4)+j);
        }
    }
    qstate[rear++]=temp;
}
int change(int state,int i)
{
    int temp=0;
    temp|=(1<<i);
    if(i%4!=0) temp|=(1<<(i-1));
    if((i+1)%4!=0) temp|=(1<<(i+1));
    if(i+4<16) temp|=(1<<(i+4));
    if(i-4>0) temp|=(1<<(i-4));
    return (state^temp);
}
bool BFS()
{
    while(top<rear)
    {
        int state=qstate[top++];
        for(int i=0;i<16;++i)
        {
            int temp;
            temp=change(state,i);
            if(state==0||state==65535)
            {
                cout<<step[state];
                return true;
            }
            else if(!r[temp])
            {
                qstate[rear++]=temp;
                r[temp]=true;
                step[temp]=step[state]+1;
            }
        }
    }
    return false;
}
int main()
{
    init();
    if(!BFS()) cout<<"Impossible"<<endl;
    return 0;
}

0 0
原创粉丝点击