poj2965 The Pilots Brothers' refrigerator
几乎与1753一样。不过flip的时候,多加了一个判断,居然就超时了。。。。。
用位运算的方法特别好,flip的操作特别快。不过没做
View Code
1 #include <stdio.h> 2 bool handlers[5][5]; //false means closed, true means open 3 bool isflip[5][5]={false}; 4 int step; 5 void flip(int row,int col) 6 { 7 int i; 8 handlers[row][col]=!handlers[row][col]; 9 isflip[row][col]=!isflip[row][col]; 10 for(i=1;i<=4;i++) //(row,col) flip 3times is equal to flip 1time.Don't use if(i!=col).It will time out. 11 handlers[row][i]=!handlers[row][i]; 12 for(i=1;i<=4;i++) 13 handlers[i][col]=!handlers[i][col]; 14 } 15 bool checkAll() 16 { 17 for(int i=1;i<=4;i++) 18 for(int j=1;j<=4;j++) 19 if(handlers[i][j]==false) 20 return false; 21 return true; 22 } 23 bool dfs(int row, int col,int deep) 24 { 25 if(deep==step) 26 return checkAll(); 27 if(row==5) 28 return false; 29 flip(row,col); 30 bool status=false; 31 if(col+1<=4) 32 status=dfs(row,col+1,deep+1); 33 else 34 status=dfs(row+1,1,deep+1); 35 if(status==true) 36 return true; 37 38 flip(row,col); 39 if(col+1<=4) 40 status=dfs(row,col+1,deep); 41 else 42 status=dfs(row+1,1,deep); 43 if(status==true) 44 return true; 45 return false; 46 } 47 int main() 48 { 49 char row[5]; 50 for(int i=1;i<=4;i++) 51 { 52 scanf("%s",row); 53 for(int j=0;j<4;j++) 54 { 55 if(row[j]=='+') 56 handlers[i][j+1]=false; 57 else 58 handlers[i][j+1]=true; 59 } 60 } 61 for(step=1;step<=16;step++) 62 { 63 if(dfs(1,1,0)==true) 64 break; 65 } 66 printf("%d\n",step); 67 for(int i=1;i<=4;i++) 68 for(int j=1;j<=4;j++) 69 if(isflip[i][j]==true) 70 printf("%d %d\n",i,j); 71 return 0; 72 73 }


浙公网安备 33010602011771号