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
题意:一个冰箱上有4*4共16个开关,改变任意一个开关的状态(即开变成关,关变成开)时,此开关的同一行、同一列所有的开关都会自动改变状态。要想打开冰箱,要所有开关全部打开才行。
思路:参考自:http://www.cnblogs.com/stdio/archive/2012/05/29/2524038.html
// 先看一个简单的问题,如何把’+’变成’-‘而不改变其他位置上的状态?
// 答案是将该位置(i,j)及位置所在的行(i)和列(j)上所有的handle更新一次。
// 结果该位置被更新了7次,相应行(i)和列(j)的handle被更新了4次,剩下的被更新了2次.
// 被更新偶数次的handle不会造成最终状态的改变.
// 因此得出高效解法,在每次输入碰到’+’的时候, 计算所在行和列的需要改变的次数
// 当输入结束后,遍历数组,所有为奇数的位置则是操作的位置,而奇数位置的个数之和则是最终的操作次数.
// 但这种算法只对n为偶数时适用
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
int mark[5][5],sum[5][5];
int vis[4][2]={0,1,0,-1,1,0,-1,0};
char map[5][5];
struct node{
int x,y,road;
};
void bfs(int x,int y)
{
node q,p;
sum[x][y]++;
queue<node>que;
q.x=x,q.y=y,q.road=0;
que.push(q);
q.x=x,q.y=y,q.road=1;
que.push(q);
q.x=x,q.y=y,q.road=2;
que.push(q);
q.x=x,q.y=y,q.road=3;
que.push(q);
mark[q.x][q.y]=1;
while(que.size())
{
q=que.front();
que.pop();
for(int i=0;i<=3;i++)
{
if(q.road==i)
{
p.x=q.x+vis[i][0];
p.y=q.y+vis[i][1];
p.road=i;
if(p.x>=1&&p.x<=4&&p.y>=1&&p.y<=4&&!mark[p.x][p.y])
{
mark[p.x][p.y]=1;
sum[p.x][p.y]++;
que.push(p);
}
}
}
}
}
int main()
{
while(~scanf("%s",map[1]+1))
{
for(int i=2;i<=4;i++)
scanf("%s",map[i]+1);
memset(sum,0,sizeof(sum));
for(int i=1;i<=4;i++)
for(int j=1;j<=4;j++)
{
if(map[i][j]=='+')
{
memset(mark,0,sizeof(mark));
bfs(i,j);
}
}
int s=0;
for(int i=1;i<=4;i++)
for(int j=1;j<=4;j++)
if(sum[i][j]%2!=0)
s++;
printf("%d\n",s);
for(int i=1;i<=4;i++)
for(int j=1;j<=4;j++)
if(sum[i][j]%2!=0)
{
printf("%d %d\n",i,j);
}
}
}