题目链接:http://poj.org/PRoblem?id=1753
Flip Game
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: Choose any one of the 16 pieces. 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).![]() 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 |
[Submit] [Go Back] [Status] [Discuss]
Home Page
Go Back
To top
题意:给你一个4*4的格子,将白块全变成黑或者将黑全变成白,问最小的反转数,反转当前个,它的上下左右都会跟着反转
解析:枚举第一行所有状态,然后根据第一行进行翻下一行,最后判断最后是否满足全为黑(白),进而更新ans
代码:
#include<iostream>#include<cstdio>#include<algorithm>#include<cstring>#include<queue>#include<cmath>#include<map>#include<vector>#include<stack>#define N 6using namespace std;const int INF = 0x3f3f3f3f;int mp1[N][N], g[N][N], mp2[N][N];int nx[4] = {-1, 0, 0, 1};int ny[4] = {0, -1, 1, 0};void fun(int i, int j) //翻转它的上下左右{ g[i][j] = !g[i][j]; for(int k = 0; k < 4; k++) { int x = i + nx[k]; int y = j + ny[k]; if(x < 0 || x > 3 || y < 0 || y > 3) continue; g[x][y] = !g[x][y]; }}int solve1(int cur) //全为白{ int ans = 0; memcpy(g, mp1, sizeof(mp1)); for(int i = 0; i < 4; i++) { if((cur>>i)&1) { ans++; fun(0, i); } } for(int i = 1; i < 4; i++) { for(int j = 0; j < 4; j++) { if(g[i - 1][j]) { ans++; fun(i, j); } } } for(int i = 0; i < 4; i++) if(g[3][i]) return INF; return ans;}int solve2(int cur) //全为黑{ int ans = 0; memcpy(g, mp2, sizeof(mp2)); for(int i = 0; i < 4; i++) { if((cur>>i)&1) { ans++; fun(0, i); } } for(int i = 1; i < 4; i++) { for(int j = 0; j < 4; j++) { if(g[i - 1][j]) { ans++; fun(i, j); } } } for(int i = 0; i < 4; i++) if(g[3][i]) return INF; return ans;}int main(){ char ch; memset(mp1, 0, sizeof(mp1)); memset(mp2, 0, sizeof(mp2)); for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { scanf(" %c", &ch); if(ch == 'b') mp1[i][j] = 1; else mp2[i][j] = 1; } } int n = 1<<4, ans = INF; for(int i = 0; i < n; i++) { ans = min(ans, solve1(i)); ans = min(ans, solve2(i)); } if(ans == INF) puts("Impossible"); else printf("%d/n", ans); return 0;}
新闻热点
疑难解答