Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 15572 | Accepted: 5856 | 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 rowi and all handles in columnj.
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
题目链接:http://poj.org/problem?id=2965
题意:有16个开关(四行四列)。+ 表示关,- 表示开。给初始状态,然后问最少需要转换开关几次。输出最少的次数,并输出装换的每个开关的坐标(坐标从1开始)。
如果有多种情况,任意输出其中一种。
开关的转换规则:每次转换该开关和其所在行和列的所有开关。
分析:和poj1753的翻棋子差不多,不同之处在于翻动的规则,另外这题在POJ 1753的基础上多了个记录路径。开始想用链表记录路径,最后改了半天还是不行,
就换了两个数组分别记录所转动的开关的横坐标和纵坐标。太弱了。。。!
代码:
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
bool m[6][6]={false};
char maps[6][6];
int step;
int flag;
int rx[20],ry[20]; //记录翻动棋子的横纵坐标。
//本来一直以为在两个for循环里把当前位置翻了,但是行和列各翻一次,翻了偶数次,相当于没翻。
void flip(int row,int col)
{
m[row][col]=!m[row][col]; //开始就是漏了这一句啊
for(int i=1;i<=4;i++)
m[row][i]=!m[row][i];
for(int j=1;j<=4;j++)
m[j][col]=!m[j][col];
}
bool judge()
{
for(int i=1;i<=4;i++)
{
for(int j=1;j<=4;j++)
{
if(m[i][j]!=false)
return false;
}
}
return true;
}
void dfs(int r,int c,int deep)
{
if(deep==step)
{
flag=judge();
return;
}
if(flag||r==5)
return;
flip(r,c);
rx[deep]=r;
ry[deep]=c;
if(c<4)
dfs(r,c+1,deep+1);
else
dfs(r+1,1,deep+1);
flip(r,c);
if(c<4)
dfs(r,c+1,deep);
else
dfs(r+1,1,deep);
}
int main()
{
for(int i=1;i<=4;i++)
{
scanf("%s",maps[i]+1);
for(int j=1;j<=4;j++)
{
if(maps[i][j]=='+')
m[i][j]=true;
}
}
for(step=0;step<=16;step++)
{
dfs(1,1,0);
if(flag) break;
}
if(flag)
{
printf("%d\n",step);
for(int k=0;k<step;k++) //从0开始,因为deep的初值为0. 到k<step,而不是<=。
printf("%d %d\n",rx[k],ry[k]);
}
return 0;
}
11919712 | Accepted | 144K | 641MS | 1372B | 2013-08-04 20:22:06 |