题目链接:http://poj.org/problem?id=2965
Time Limit: 1000MS Memory Limit: 65536K
Problem 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
Northeastern Europe 2004, Western Subregion
题目分析
在深搜的过程中使用tempx[i],tempy[i]保存临时的路径,用fx[i],fy[i]保存最终的路径,在dfs(int i,int j,int b)中,i,j表示当前位置,b表示已经翻的次数。
AC代码
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#define ll long long
#define ull unsigned long long
#define rep(i,a,b) for (int i=(a),_ed=(b);i<=_ed;i++)
#define rrep(i,a,b) for(int i=(a),_ed=(b);i>=_ed;i--)
#define fil(a,b) memset((a),(b),sizeof(a))
#define cl(a) fil(a,0)
#define PI 3.1415927
#define inf 0x3f3f3f3f
using namespace std;
char mat[6][6];
int maxstep,flag=0;
int tempx[20];
int tempy[20];
int fx[20];
int fy[20];
int res=inf;
int judge()
{
rep(i, 1, 4)
{
rep(j, 1, 4) if (mat[i][j] != '-') return 0;
}
return 1;
}
void turn(int x, int y)
{
if (mat[x][y] == '+') mat[x][y] = '-';
else mat[x][y] = '+';
}
void flip(int x, int y)
{
rep(i, 1, 4) turn(x, i);
rep(i, 1, 4) if (i != x) turn(i, y);
}
void dfs(int i, int j, int b)
{
if (judge())
{
if (res > b)
{
res = b;
rep(i, 1, res)
{
fx[i] = tempx[i];
fy[i] = tempy[i];
}
}
}
if (i == 5) return;
if (j == 4) dfs(i + 1, 1, b);
else dfs(i, j + 1, b);
flip(i, j);
tempx[b + 1] = i;
tempy[b + 1] = j;
if (j == 4) dfs(i + 1, 1, b+1);
else dfs(i, j + 1, b+1);
flip(i, j);
}
int main(void)
{
cl(mat);
rep(i, 1, 4)
{
rep(j, 1, 4) cin >> mat[i][j];
}
dfs(1,1,0);
cout << res << endl;
rep(i, 1, res) cout << fx[i] << " " << fy[i] << endl;
return 0;
}
2016 年 09月 18日