【枚举 位运算】POJ_2965 The Pilots Brothers' refrigerator

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/SSL_hzb/article/details/89577378

题意

给出一个 4 4 4*4 的棋盘,其中每个格子有两种状态 + + - 。对一个格子进行操作可以使得格子所在的行和列状态全部取反,求出最少步数使得棋盘格子全部都为 -

思路

由于范围很小,所以我们可以直接暴力枚举格子选或不选的情况,状态压缩判断即可。

代码

#include<cstdio>

int ans;
int a[5][5], x[17], y[17], ansx[17], ansy[17], state[5];
char c;

int check(int n) {
	int t[5];
	for (int i = 1; i <= 4; i++)
		t[i] = state[i];
	for (int i = 1; i <= n; i++) {
		t[x[i]] ^= (1 << 4) - 1;
		for (int j = 1; j <= 4; j++)
			if (x[i] != j)
				t[j] ^= (1 << 4 - y[i]);
	}
	return !(t[1] | t[2] | t[3] | t[4]);
}

void dfs(int p, int s) {
    if (s >= ans) return;
    if (check(s)) {
    	ans = s;
    	for (int i = 1; i <= ans; i++)
    		ansx[i] = x[i], ansy[i] = y[i];
    	return;
    }
    if (p == 16) return;
	x[s + 1] = p / 4 + 1;
	y[s + 1] = p % 4 + 1;
	dfs(p + 1, s + 1);
	dfs(p + 1, s);
}

int main() {
    for (int i = 1; i <= 4; i++, c = getchar())
        for (int j = 1; j <= 4; j++) {
            scanf("%c", &c);
            a[i][j] = c == '+';
        }
    for (int i = 1; i <= 4; i++)
    	for (int j = 1; j <= 4; j++)
    		state[i] |= a[i][j] << (4 - j);
    ans = 17;
	dfs(0, 0);
	printf("%d\n", ans);
	for (int i = 1; i <= ans; i++)
        printf("%d %d\n", ansx[i], ansy[i]);
}

猜你喜欢

转载自blog.csdn.net/SSL_hzb/article/details/89577378