Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 17546 | Accepted: 6640 | 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
题意就不多说了,很容易理解,代码里有详细解释(在poj里c++情况下提交超时,G++下提交576ms水过)
附上AC代码:
#include<iostream> #include<queue> #include<stack> #include<cstring> using namespace std; struct Node{ int x,y; int pre; }dxy[1<<16]; //记录bfs路径 int step[1<<16],vis[1<<16]; //vis表示当前id是否已经历遍,step表示当前id下的翻转次数 int flag; void bfs(int id){ flag=0; if(id==0){ cout<<'0'<<endl; return ; } memset(vis,0,sizeof(vis)); queue <int> q; while(!q.empty()) q.pop(); step[id]=0; vis[id]=1; q.push(id); //从当前id出发bfs,历遍所有的情况 while(!q.empty()){ int tmp=q.front(); q.pop(); id=tmp; //16个方格分别翻转一次,按照规则再在各自的基础上接着翻转,直到成功为止 for(int i=0;i<4;i++) for(int j=0;j<4;j++){ tmp=id; tmp^=15<<(12-4*i); //将i所在行全部数字取反 tmp^=(4369^(1<<(12-4*i)))<<(3-j); //将j所在列全部数字取反(^(1<<(12-4*i))目的是除i j位置数字,避免重复取反) if(tmp==0){ cout<<step[id]+1<<endl; flag=1; dxy[tmp].pre=id; dxy[tmp].x=i+1; dxy[tmp].y=j+1; return ; } if(!vis[tmp]){ q.push(tmp); vis[tmp]=1; step[tmp]=step[id]+1; dxy[tmp].pre=id; //记录路径 dxy[tmp].x=i+1; dxy[tmp].y=j+1; } } } return ; } int outdxy(int id){ int pre_id=0; stack <Node> s; while(!s.empty()) s.pop(); while(pre_id!=id){ s.push(dxy[pre_id]); pre_id=dxy[pre_id].pre; } while(!s.empty()){ Node tmp=s.top(); s.pop(); cout<<tmp.x<<' '<<tmp.y<<endl; } } int main(){ //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); char ch; int id=0; // id用来表示当前输入的布局 //注意左边为高位,右边为低位,后面bfs时要特别注意 for(int i=0;i<16;i++){ cin>>ch; id<<=1; //左移一位的位运算,十进制里相当于乘以2 if(ch=='+') id+=1; } bfs(id); if(flag) outdxy(id); return 0; }