Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 17384 | Accepted: 6576 | Special Judge |
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
Source
解题分析:
此题我也是参考了网上一位大神的做法,非常简单明了。
先看一个简单的问题,如何把'+'变成'-'而不改变其他位置上的状态?
答案是将该位置(i,j)及位置所在的行(i)和列(j)上所有的handle更新一次。
被更新偶数次的handle不会造成最终状态的改变.
因此得出高效解法,在每次输入碰到'+'的时候, 计算所在行和列的需要改变的次数
当输入结束后,遍历数组,所有为奇数的位置则是操作的位置,而奇数位置的个数之和则是最终的操作次数.
代码:
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
#define MAX_N 4
int main()
{
int handles[MAX_N][MAX_N] = {0};
int i, j, k;
int count = 0; //定义一共进行了几次操作
char c; //缓存字符
for (i = 0; i < MAX_N; ++i)
{
for (j = 0; j < MAX_N; ++j)
{
scanf("%c",&c);
if ('+' == c) //判断字符,然后进行操作
{
handles[i][j]++;
for (k = 0; k < MAX_N; ++k)
{
handles[i][k]++;
handles[k][j]++;
}
}
}
getchar(); //此处非常重要,如果不加会造成加国的偏差,自己可以试试
}
for (i = 0; i < MAX_N; ++i) //判断是否为奇数然后进行操作数计和
{
for (j = 0; j < MAX_N; ++j)
{
if (handles[i][j] % 2)
{
count++;
}
}
}
cout<<count<<endl;
for (i = 0; i < MAX_N; ++i)
{
for (j = 0; j < MAX_N; ++j)
{
if (handles[i][j] % 2)
{
cout<<(i+1)<<" "<<(j+1)<<endl;
}
}
}
return 0;
}