a698中等取石遊戲的必勝與必敗狀態

CPE:Bachet’s Game (UVa 10404)

從空桌的必敗狀態向上推導最佳策略。

前往題目練習 →回報教學錯誤每局時間 O(nm),空間 O(n)。

解題思路

win[s]表示輪到操作且剩s顆時是否有必勝策略。win[0]=false,因為已沒有石頭可取;若存在合法取量a≤s使win[s−a]為false,就能把必敗局面交給對手,因此win[s]=true。若所有合法後繼都必勝,目前就必敗。

取量都是正數,所以每個後繼石頭數更小,從1算到n即可,無須搜尋整棵博弈樹。集合含1確保正數局面都有操作。先排序取量,遇到比s大者即可停止;找到一個必敗後繼也可提早停止。輸入直到EOF,n的狀態為真印 Stan wins,否則 Ollie wins。

Step-by-step animation

示意:可取1、3顆,n=4

回報動畫錯誤
步驟 1 / 3

0與1

0必敗;1可取1交給0,所以必勝。

0:敗
1:勝
win[1]
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
    int n, m;
    while (cin >> n >> m) {
        vector<int> moves(m);
        for (int &x : moves)
            cin >> x;
        sort(moves.begin(), moves.end());
        vector<unsigned char> win(n + 1);
        for (int s = 1; s <= n; s++)
            for (int a : moves) {
                if (a > s)
                    break;
                if (!win[s - a]) {
                    win[s] = 1;
                    break;
                }
            }
        cout << (win[n] ? "Stan wins" : "Ollie wins") << '\n';
    }
}

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

更多