POJ 1753 Flip Game

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 since the 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;// black
			else 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值