Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions:12619 | Accepted: 8003 |
Description

The aim of the game is, starting from any initial set of lights on in the display, to press buttons to get the display to a state where all lights are off. When adjacent buttons are pressed, the action of one button can undo the effect of another. For instance, in the display below, pressing buttons marked X in the left display results in the right display.Note that the buttons in row 2 column 3 and row 2 column 5 both change the state of the button in row 2 column 4,so that, in the end, its state is unchanged.

Note:
1. It does not matter what order the buttons are pressed.
2. If a button is pressed a second time, it exactly cancels the effect of the first press, so no button ever need be pressed more than once.
3. As illustrated in the second diagram, all the lights in the first row may be turned off, by pressing the corresponding buttons in the second row. By repeating this process in each row, all the lights in the first
four rows may be turned out. Similarly, by pressing buttons in columns 2, 3 ?, all lights in the first 5 columns may be turned off.
Write a program to solve the puzzle.
Input
Output
Sample Input
2 0 1 1 0 1 0 1 0 0 1 1 1 0 0 1 0 0 1 1 0 0 1 0 1 0 1 1 1 0 0 0 0 1 0 1 0 1 0 1 0 1 1 0 0 1 0 1 1 1 0 1 1 0 0 0 1 0 1 0 0
Sample Output
PUZZLE #1 1 0 1 0 0 1 1 1 0 1 0 1 0 0 1 0 1 1 1 0 0 1 0 0 0 1 0 0 0 0 PUZZLE #2 1 0 0 1 1 1 1 1 0 0 0 0 0 0 0 1 0 0 1 1 0 1 0 1 1 0 1 1 0 1
Source
灯只有按和不按两种状态,如果a[i][j]是亮的,那么可以通过点a[i+1][j]将其熄灭,所以我们只要枚举第一排灯的所有可能,然后逐步递推到最后一行,如果最后一行的灯全部熄灭,那就说明这种方案可行。
以下是ac代码(位运算+二进制数枚举):
#include<iostream>
#include<cstdio>
using namespace std;
char orlights[5];
char lights[5];
char result[5];
int getbit(char c,int i){
return (c>>i)&1;
}
void setbit(char & c,int i,int v){
if(v){
c|=(1<<i);
}else{
c&=~(1<<i);
}
}
void printresult(int t){
cout<<"PUZZLE #"<<t<<endl;
for(int i=0;i<5;i++){
for(int j=0;j<6;j++){
cout<<getbit(result[i],j);
if(j<5){
cout<<" ";
}
}
cout<<endl;
}
}
void flipbit(char & c,int i){
c^=(1<<i);
}
int main(){
int T;
cin>>T;
for(int t=1;t<=T;t++){
for(int i=0;i<5;i++){
for(int j=0;j<6;j++){
int s;
cin>>s;
setbit(orlights[i],j,s);
}
}
for(int n=0;n<64;n++){
int switchs=n;
memcpy(lights,orlights,sizeof(orlights));
for(int i=0;i<5;i++){
result[i]=switchs;
for(int j=0;j<6;j++){
if(getbit(switchs,j)){
if(j>0)flipbit(lights[i],j-1);
flipbit(lights[i],j);
if(j<5)flipbit(lights[i],j+1);
}
}
if(i<4)lights[i+1]^=switchs;
switchs=lights[i];
}
if(lights[4]==0){
printresult(t);
break;
}
}
}
return 0;
}