ACM POJ 2965 The Pilots Brothers' refrigerator
http://poj.org/problem?id=2965
Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 10158 | Accepted: 3707 | 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
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
const int MAXN=65536;
int que[MAXN*2];
int pre[MAXN];
int prei[MAXN];
int prej[MAXN];
int step[MAXN];
void bfs(int p)
{
int i,j,rear, front;
rear=front=0;
que[rear++]=p;
memset(pre,-1,sizeof(pre));
memset(step,0,sizeof(step));
memset(prei,-1,sizeof(prei));
memset(prej,-1,sizeof(prej));
pre[p]=p;
//step[p]++;
while(front<rear)
{
int tmp=que[front++];
int t=tmp;
for(i=0;i<=3;i++)
for(j=0;j<=3;j++)
{
tmp=t;
tmp^=1<<(15-j);
tmp^=1<<(15-j-4);
tmp^=1<<(15-j-8);
tmp^=1<<(15-j-12);
tmp^=1<<(15-4*i);
tmp^=1<<(15-4*i-1);
tmp^=1<<(15-4*i-2);
tmp^=1<<(15-4*i-3);
tmp^=1<<(15-4*i-j);//(i,j)多倒了一次,倒回去
if(pre[tmp]==-1)
{
pre[tmp]=t;
step[tmp]=step[t]+1;
prei[tmp]=i+1;
prej[tmp]=j+1;
que[rear++]=tmp;
}
if(tmp==0)
{
printf("%d\n",step[tmp]);
int x,y,n;
int a[MAXN],b[MAXN];
n=x=y=step[tmp];
while(pre[tmp]!=tmp)
{
a[x--]=prei[tmp];
b[y--]=prej[tmp];
tmp=pre[tmp];
}
for(int k=1;k<=n;k++)
{
printf("%d %d\n",a[k],b[k]);
}
return;
}
}
}
}
int main()
{
freopen("test.in","r",stdin);
freopen("test.out","w",stdout);
int n=0;
char ch;
int i,j;
for(i=0;i<4;i++)
for(j=0;j<4;j++)
{
cin>>ch;n<<=1;
if(ch=='+')n+=1;
}
bfs(n);
return 0;
}