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冰箱开关,+为关,-为开,给你一个起始状态,每次可以选择一个开关,将它连同它所在的行列一起翻转状态,求最小次数,并输出操作
题解:前一道题可以爆枚,但毕竟期望标程是bfs或dfs,所以本题我来了一份bfs
首先
因为只有4*4的大小,每个坐标(x,y)上只有两种情况,所以可以考虑把十六个位置压成一个数
然后要反转哪个位置,就只需要给该位置xor上一个数就可以了
如果要反转一堆呢?
那只需要xor这一堆位置的二进制值即可
所以先预处理好改变(1,1)-(4,4)每个点要xor上的值(推荐还是用程序预处理,手算错误较高)
然后bfs状态
至于为什么要bfs呢?
因为bfs有着优越性,因为进入队列的状态按步数从小到大排,可以保证搜到的第一个解一定是最小的
终止条件为所有的开关都被翻好了,即sta为0或65535(随自己定义的关为1或开为1而定)
至于记录路径吗emmmm和一道floyd求最小环的记录路径很像
记录转移过来的状态,然后追溯回去,依次输出。
代码:
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define fa puts("fuck");
using namespace std; struct node
{
int state,s;
node(int a,int b)
{
state=a;
s=b;
}
}; struct node2
{
int pa;
int i;
} path[]; int vis[],sum,map[][]; int change[]=
{
,,,,
,,,,
,,,,
,,,
}; void print(int k)
{
if(path[k].pa==sum)
{
cout<<path[k].i/+<<" "<<path[k].i%+<<endl;
return;
}
print(path[k].pa);
cout<<path[k].i/+<<" "<<path[k].i%+<<endl;
} void bfs()
{
memset(vis,,sizeof(vis));
vis[sum]=;
queue<node> q;
q.push(node(sum,));
while(!q.empty())
{
node t=q.front();
q.pop();
if(t.state==)
{
cout<<t.s<<endl;
print(t.state);
return ;
}
for(int i=; i<; i++)
{
int tsta=t.state^change[i];
int ts=t.s+;
if(!vis[tsta])
{
q.push(node(tsta,ts));
vis[tsta]=;
path[tsta].pa=t.state;
path[tsta].i=i;
}
}
}
} int main()
{
char c;
int cnt=;
for(int i=; i<=; i++)
{
for(int j=; j<=; j++)
{
cin>>c;
if(c=='-')
{
map[i][j]=;
sum+=(<<cnt);
}
else
{
map[i][j]=;
}
cnt--;
}
}
bfs();
return ;
}