poj 1753 Flip Game(枚举)

枚举所有情况,每个位置可能变也可能不变,复杂度O(2^16)。

View Code
 1 /*
 2 Author:Zhaofa Fang
 3 Lang:C++
 4 */
 5 #include <cstdio>
 6 #include <cstdlib>
 7 #include <iostream>
 8 #include <cmath>
 9 #include <cstring>
10 #include <algorithm>
11 #include <string>
12 #include <utility>
13 #include <vector>
14 #include <queue>
15 #include <stack>
16 #include <map>
17 #include <set>
18 using namespace std;
19 typedef long long ll;
20 #define pii pair<int,int>
21 #define pb push_back
22 #define mp make_pair
23 #define fi first
24 #define se second
25 #define lowbit(x) (x&(-x))
26 #define INF 2147483647;
27 
28 int tot,ans;
29 int a[17];
30 char str[17][17];
31 void change(int x)
32 {
33     a[x]^=1;
34     if(x-4>0)
35     {
36         a[x-4]^=1;
37     }
38     if(x-1>0 && (x-1)%4)
39     {
40         a[x-1]^=1;
41     }
42     if(x+1<17 && x%4)
43     {
44         a[x+1]^=1;
45     }
46     if(x+4<17)
47     {
48         a[x+4]^=1;
49     }
50 }
51 bool check()
52 {
53     int cnt=0;
54     for(int i=1;i<=16;i++)cnt+=a[i];
55     if(cnt % 16 == 0)return true;
56     else return false;
57 }
58 int tmp[17];
59 void dfs(int cur)
60 {
61     if(cur > 16)
62     {
63         if(check())
64         {
65             if(tot < ans)ans = tot;
66         }
67         return;
68     }
69     dfs(cur+1);
70     change(cur);tmp[tot]=cur;
71     tot++;
72     dfs(cur+1);
73     tot--;
74     change(cur);
75 
76 }
77 int main()
78 {
79     #ifndef ONLINE_JUDGE
80     freopen("in","r",stdin);
81     #endif
82     int len=0;
83     for(int i=0;i<4;i++)
84     {
85         scanf("%s",str[i]);
86         for(int j=0;j<4;j++)
87         if(str[i][j] == 'b')a[++len]=1;
88         else a[++len]=0;
89     }
90     tot=0;ans=(1<<16);
91     dfs(1);
92     if(ans != (1<<16))printf("%d\n",ans);
93     else puts("Impossible");
94     return 0;
95 }
by Farmer
原文地址:https://www.cnblogs.com/fzf123/p/2719140.html