题目链接:http://poj.org/problem?id=2965
The Pilots Brothers’ refrigerator
Time Limit: 1000MS Memory Limit: 65536K
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的图,要通过翻转将图全改为‘-’,并打印出翻转过程,每次翻转一个点,这个点所在的行和列也要同时翻转。
刚看到的时候就以为是POJ1753题的升级版 ,其实这也是一个思维题,要翻转一个点并且除了这个点外其他点不变,就只能将这个点所在的行列上所有的点都给翻转一下。然而一个点如果翻转偶数次就和没翻转的效果一样。这样在实现的时候就可以开一个4*4的int数组,每个是‘+’的点它所在的行列上的点全加一,最后将这个int数组上的所有的数全mod2,如果int数组中1的个数就是需要翻转的次数,1所在的点就是需要翻转的点。
然而自己在写这个题的时候用poj1753的思路写了个bfs超时了,看到网上都是用dfs过的好像没有bfs。
丑代码:
#include<stdio.h>
using namespace std;
const int maxn = 10;
char s[maxn][maxn];
int maps[maxn][maxn];
void deal(int x,int y)
{
int x2,y2;
maps[x][y]++;
//上下作业操作
x2 = x-1;
while(x2>=0)
{
maps[x2][y]++;
x2--;
}
y2 = y-1;
while(y2>=0)
{
maps[x][y2]++;
y2--;
}
x2 = x+1;
while(x2<4)
{
maps[x2][y]++;
x2++;
}
y2 = y+1;
while(y2<4)
{
maps[x][y2]++;
y2++;
}
}
void solve()
{
for(int i=0;i<4;i++)
scanf("%s",s[i]);
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
{
if(s[i][j] == '+')
deal(i,j);
}
int sum = 0;
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
{
maps[i][j] = maps[i][j]%2;
if(maps[i][j])
sum++;
}
printf("%d
",sum);
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
{
if(maps[i][j])
printf("%d %d
",i+1,j+1);
}
return ;
}
int main()
{
solve();
}