题意
请参考LRJ白书第一章例题7.
思路
大概是个带有机智成分的枚举。
为什么这么说,因为这道题的关键思路点就是发现只要知道第一行,就可以构造出整个数表,这样我们只要枚举第一行就可以解决问题,复杂度直接降低了一次幂。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
#include <iostream> #include <algorithm> #include <queue> #include <vector> #include <cstdlib> #include <cstdio> #include <string> #include <cstring> #include <ctime> #include <iomanip> #include <cmath> #include <set> #include <stack> #include <cmath> #include <map> #include <complex> using namespace std; int n; int per[16]; int orig[16][16]; int now[16][16]; void genPermutation(int s){ int cur = n; while(cur){ if(s&1){ per[cur] = 1; }else{ per[cur] = 0; } cur--; s >>= 1; } } void genNow(){ memset(now,0,sizeof(now)); for(int i = 1; i <= n; i++){ now[1][i] = per[i]; } for(int i = 1; i < n; i++){ for(int j = 1; j <= n; j++){ int cnt = now[i-1][j] + now[i][j-1] + now[i][j+1]; if(cnt % 2){ now[i+1][j] = 1; }else{ now[i+1][j] = 0; } } } } int compare(){ int ret = 0; for(int i = 1; i <= n; i++){ for(int j = 1; j <= n; j++){ if(now[i][j] == 0 && orig[i][j] == 1){ return 0x3f3f3f3f; } if(now[i][j] != orig[i][j]){ ret++; } } } return ret; } int main(){ int caseCnt; scanf(" %d",&caseCnt); for(int d = 1; d <= caseCnt; d++){ scanf(" %d",&n); for(int i = 1; i <= n; i++){ for(int j = 1; j <= n; j++){ scanf(" %d",&orig[i][j]); } } int res = 0x3f3f3f3f; for(int i = 0; i < (1 << n); i++){ genPermutation(i); genNow(); res = min(res,compare()); } if(res == 0x3f3f3f3f){ res = -1; } printf("Case %d: %d\n",d,res); } return 0; } |