a932困難

112 臺北市資訊學科能力競賽(2023)|魔法師(Magician)

以存活者排名跳到每輪輸家。

解題思路

Fenwick樹每個存活魔法師存1。pos是下一輪起念者在存活者中的0起算排名,輸家的排名為(pos+S−1)%alive。以Fenwick二進位提升找該排名的原編號,並累計輸次。

若輸家退出,就刪除其1,下一位在新存活序列的排名仍是剛才的輸家排名(對新alive取餘);若未退出,下一輪從其後一名開始。這精確模擬每句輪流且避免逐句走S步。直到alive=1時查出剩餘者。

最多NK輪,時間O(NK log N),空間O(N);使用迭代操作無深遞迴。 Python read().split() 另需 O(I) 輸入文字與詞元暫存,I 為總輸入大小。

Step-by-step animation

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

回報動畫錯誤
步驟 1 / 3

示意N=3,S=3,K=1

存活排名0,1,2,第一輪輸家為3。

1
2
3
輸家排名
2

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    int n, S, K;
    cin >> n >> S >> K;
    vector<int> bit(n + 1), loss(n + 1);
    for (int i = 1; i <= n; i++)
        bit[i] = i & -i;
    auto kth = [&](int k) {
        int x = 0;
        for (int step = 1 << __lg(n); step; step >>= 1)
            if (x + step <= n && bit[x + step] <= k) {
                k -= bit[x + step];
                x += step;
            }
        return x + 1;
    };
    int alive = n, pos = 0;
    while (alive > 1) {
        pos = (pos + S - 1) % alive;
        int x = kth(pos);
        if (++loss[x] == K) {
            for (int i = x; i <= n; i += i & -i)
                bit[i]--;
            alive--;
            pos %= alive;
        } else
            pos = (pos + 1) % alive;
    }
    cout << kth(0) << '\n';
}

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

更多