[PKU3279]Fliptile [USACO 2007 Open]

好熟悉的开关灯问题。实际上,要消去某一行,必须要靠下一行,而且下一行的策略恰恰好就是上一行的状态。因此如果我们第一行确定了,下面的所有行也就都确定了。

所以这题的方法就是:枚举第一行按法,接下来根据题意模拟按灯,复杂度为O(2^n*nm)。要注意按灯不完全和异或相同,因此难以用位运算优化。另外一定要注意最后一行按过之后是不是空的,只有当空的时候才是有效状态。
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
#include <cstdio>
#include <bitset>
#include <cstring>
int m, n, ans(0x7FFFFFFF);
typedef std::bitset<16> set;
set a[16], b[16], answer[16];
inline void flip(set& now, set& next, const int col)
{
  now.flip(col), next.flip(col);
  if (col-1 >= 0) now.flip(col-1);
  if (col+1 < n) now.flip(col+1);
}
int main()
{
  scanf("%d%d", &m, &n);
  const int FULL = (1<<n)-1;
  for (int i = 0; i < m; ++i)
    for (int j = 0, x; j < n; ++j)
    {
      scanf("%d", &x);
      a[i].set(j, x);
    }
  for (int first = 0; first <= FULL; ++first)
  {
    int sum = 0;
    b[0] = first;
    std::bitset<16> next(a[0]), now;
    for (int i = 0; i < m; ++i)
    {
      now = next, next = a[i+1];
      for (int j = 0; j < n; ++j)
        if (b[i].test(j))
          flip(now, next, j);
      b[i+1] = now;
    }
    if (now.none() && sum < ans)
    {
      ans = sum;
      memcpy(answer, b, sizeof(answer));
    }
  }
  if (ans == 0x7FFFFFFF)
  {
    printf("IMPOSSIBLE");
    return 0;
  }
  for (int i = 0; i < m; ++i)
  {
    for (int j = 0; j < n; ++j)
      printf("%d ", answer[i].test(j) ? 1 : 0);
    printf("n");
  }
}

Comments