#POJ1753#Flip Game(位运算+BFS)

来源:互联网 发布:视频广告拦截软件 编辑:程序博客网 时间:2024/05/07 15:12

Flip Game

 

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

位运算的题,每个棋子只有两种状态,1表示‘b’,0表示‘w’,一共16种操作(每次op[i]^取反),找到了就输出

Code:

StatusAcceptedTime79msMemory300kBLength896LangC++Submitted2017-02-23 15:49:38SharedRemoteRunId16630356

#include<iostream>#include<cstdio>#include<queue>#include<cstdlib>using namespace std;struct node{int id,step;node(){}node(int a,int b){id=a,step=b;}};int Ans=0x3f3f3f3f;int op[16]={51200,58368,29184,12544,35968,20032,10016,4880,2248,1252,626,305,140,78,39,19};bool vis[(1<<17)-1];void Bfs(int S){if(!S||S==0xffff){Ans=0;return ;}vis[S]=1;queue<node>q;q.push(node(S,0));while(!q.empty()){node tmp=q.front();q.pop();for(int i=0; i<16; ++i){int now=tmp.id^op[i];if(!now||now==0xffff){Ans=tmp.step+1;return ;}if(!vis[now]){vis[now]=1;q.push(node(now,tmp.step+1));}}}return ;}int main(){int S=0;char s[6];for(int i=0; i<4; ++i){scanf("%s",s);for(int j=0; j<4; ++j){S<<=1;if(s[j]=='b')S+=1;}}Bfs(S);if(Ans==0x3f3f3f3f)printf("Impossible\n");else printf("%d\n",Ans);return 0;}


0 0
原创粉丝点击