一、题目描述
poj 2965
Description
The game “The Pilots Brothers: following the stripy elephant” has a quest where a player needs to open a refrigerator.
There are 16 handles on the refrigerator door. Every handle can be in one of two states: open or closed. The refrigerator is open only when all handles are open. The handles are represented as a matrix 4х4. You can change the state of a handle in any location [i, j] (1 ≤ i, j ≤ 4). However, this also changes states of all handles in row i and all handles in column j.
The task is to determine the minimum number of handle switching necessary to open the refrigerator.
Input
The input contains four lines. Each of the four lines contains four characters describing the initial state of appropriate handles. A symbol “+” means that the handle is in closed state, whereas the symbol “−” means “open”. At least one of the handles is initially closed.
Output
The first line of the input contains N – the minimum number of switching. The rest N lines describe switching sequence. Each of the lines contains a row number and a column number of the matrix separated by one or more spaces. If there are several solutions, you may give any one of them.
Sample Input
-+–
-+–
Sample Output
6
1 1
1 3
1 4
4 1
4 3
4 4
二、解答
这道题类似之前的棋盘反转,poj 1753 但是之前那道题不需要记录路径,很容易就可以得出答案,直接采用二叉树结构,每颗棋子翻与不翻即可。
不过在网上找到一个比较牛逼的解答方案。这里来解释下。
1.规律
要将某个 ‘+’ 反转为 ‘-’,则同行、同列都需要变换,这样做的话,自己被反转了 7 次,同行或同列的其他棋子被反转了 4 次,不再同行或者同列的棋子需要反转2次。反转偶数次和没有反转一样,反转奇数次和反转一次一样。这样我们只需要遍历 ‘+’的点,将同行同列的访问次数++即可,然后将自己再–。遍历完所有的‘+’后,访问次数为 1 的点就是被翻过的点,然后在计算下真正的坐标点即可。
import java.util.*;
public class Main{
static int answer,dataIn;
static final int size = 16;
static int[] input = new int[size], times = new int[size],data = new int[size];
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String line = "";
for (int i = 0; i < 4; i++) {
line = sc.next();
for (int j = 0; j < 4; j++) {
data[dataIn++] = line.charAt(j);
}
}
for (int i = 0; i < 16; i++) {
if (data[i] == '+') {
int row = i / 4;
int column = i % 4;
input[i] = 1;
times[row * 4]++;
times[row * 4 + 1]++;
times[row * 4 + 2]++;
times[row * 4 + 3]++;
times[column]++;
times[4 + column]++;
times[8 + column]++;
times[12 + column]++;
times[row * 4 + column]--;
}
}
for (int i = 0; i < 16; i++) {
if (times[i] % 2 != 0) {
answer++;
}
}
System.out.println(answer);
for (int i = 0; i < 16; i++) {
if (times[i] % 2 != 0) {
System.out.println(((i / 4) + 1) + " " + ((i % 4) + 1));
}
}
}
}