a906中等

100 全國資訊學科能力競賽(2011)|新井字遊戲

在4096個遮罩上計算勝負。

解題思路

以12-bit遮罩表示棋子。預先建立所有單點與題目12條相鄰邊的雙點取法;只可移除遮罩中完整存在的取法。

空局面設為必勝,因為剛取完最後棋子的對手已輸。非空局面只要能移到必敗局面就是必勝,否則必敗。每次取棋子都會減少遮罩值,故由小到大求值即可。

預處理 O(2^12×24),每筆查詢 O(12),空間 O(2^12)。 Python read().split() 另需 O(I) 輸入文字與詞元暫存,I 為總輸入大小。

Step-by-step animation

教學示意(以步驟描述中的輸入為準)

回報動畫錯誤
步驟 1 / 3

一枚棋子

只有A時必須取最後一子,先手輸。

A
勝負
0

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    vector<int> moves;
    for (int i = 0; i < 12; i++)
        moves.push_back(1 << i);
    for (string e : vector<string>{"AD", "DH", "HK", "BE", "EI", "IL", "CD", "DE", "EF",
                                   "GH", "HI", "IJ"})
        moves.push_back((1 << (e[0] - 'A')) | (1 << (e[1] - 'A')));
    vector<int> w(4096);
    w[0] = 1;
    for (int s = 1; s < 4096; s++)
        for (int t : moves)
            if ((s & t) == t && !w[s ^ t])
                w[s] = 1;
    int n;
    cin >> n;
    while (n--) {
        string s;
        cin >> s;
        int mask = 0;
        for (int i = 0; i < 12; i++)
            if (s[i] == '1')
                mask |= 1 << i;
        cout << w[mask];
    }
    cout << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多