解題思路
以 13 位元 mask 表示仍有鐵圈的位置。合法操作是刪去一位,或刪去題目鄰接表中同時存在的兩位。
把空盤設成勝態 win[0]=true:這是為了讓拿走最後鐵圈的操作不可能成為致勝操作,而不是說空盤還能實際下棋。
非空狀態只要存在一個操作可走到敗態,就是勝態;否則所有操作都把優勢送給對手,是敗態。刪位後數字必定減少,因此由小到大填表即可歸納證明正確。
預處理 O(2^13 × (13+24)) 時間、O(2^13) 空間;每筆查詢 O(1)。 Python一次讀入另佔O(輸入文字長度)空間。
Step-by-step animation
示例:拿掉唯一鐵圈就輸,因此狀態 1 是敗態。
步驟 1 / 3
只剩位置 0
拿掉唯一鐵圈就輸,因此狀態 1 是敗態。
0
- mask
- 1
- win
- 0
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<pair<int, int>> e = {{0, 2}, {0, 3}, {1, 2}, {2, 3}, {3, 4}, {1, 5},
{2, 5}, {2, 6}, {3, 6}, {3, 7}, {4, 7}, {5, 6},
{6, 7}, {5, 8}, {5, 9}, {6, 9}, {6, 10}, {7, 10},
{7, 11}, {8, 9}, {9, 10}, {10, 11}, {9, 12}, {10, 12}};
vector<int> moves;
for (int i = 0; i < 13; i++)
moves.push_back(1 << i);
for (auto [a, b] : e)
moves.push_back((1 << a) | (1 << b));
vector<int> w(8192);
w[0] = 1;
for (int s = 1; s < 8192; s++)
for (int m : moves)
if ((s & m) == m && !w[s ^ m]) {
w[s] = 1;
break;
}
int n, s;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> s;
if (i)
cout << ' ';
cout << w[s];
}
cout << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。