POJ 1753 Flip Game

来源:互联网 发布:部落哥布林升级数据 编辑:程序博客网 时间:2024/06/07 18:10

Thinking: This one we used the enumeration method. Try the integer from 1 to 2^16 and use bits inside it to imitate different situations. We can have choices on each piece whether we flip it or not sincethe sequence doesn't matter. 


AC code:

#include<iostream>#define FIND_i(num) (num%4)#define FIND_j(num) (num/4)#define MIN(a,b) ((a)<(b)?(a):(b))using namespace std;int bits[16];int di[5] = { 0, 0, 1, -1,0 };int dj[5] = { 1, -1, 0, 0,0 };int cpysize = 16 * sizeof(int);inline bool ok(int sample[]){for (int i = 0; i < 15; i++){if (sample[i] != sample[i + 1])return false;}return true;}inline int check_validity(int arrange){int ans = 0;int sample[16];int matrix[4][4];memcpy(sample, bits, cpysize);for (int i = 0; i <= 15; i++){matrix[FIND_i(i)][FIND_j(i)] = sample[i];}for (int i = 0; i <= 15; i++)// change sample{if ((arrange >> i) & 1){ans++;for (int k = 0; k <= 4; k++){int new_row = FIND_i(i) + di[k];int new_col = FIND_j(i) + dj[k];if (new_row <= 3 && new_row >= 0 && new_col <= 3 && new_col >= 0){int num = new_row * 4 + new_col;sample[num] = sample[num] ^ 1;}}}}if (ok(sample)){return ans;}else return -1;}int main(){char str[5];int count = 0;for (int i = 1; i <= 4; i++){scanf("%s", str);for (int j = 0; j <= 3; j++){if (str[j] == 'b')bits[count++] = 1;// blackelse bits[count++]= 0;//white}}if (ok(bits)){printf("0\n");return 0;}int lim = 1 << 16;int min_effort = 0x3f3f3f3f;bool impossible = true;for (int i = 1; i <= lim; i++){int result = check_validity(i);if (result > 0){impossible = false;min_effort = MIN(result, min_effort);}}if (impossible)printf("Impossible\n");else printf("%d\n", min_effort);return 0;}


0 0