a119中等循環時間・出現位置二分搜尋

TOI 2022/10 潛力組:卡牌遊戲

每張頂牌直接跳到下一次可出的回合,避免逐回合模擬。

前往題目練習 →回報教學錯誤預處理 O(K+輪盤輸入字元數),所有玩家 O(NM log K),空間 O(K+M+N)(Python 另有全部輸入字元的暫存);K≤3000、NM≤10⁶。

解題思路

先為輪盤上的每種數字建立遞增的出現位置表,位置從 1 起算。牌面只有 0~49,所以更大的輪盤數字不需要保存;C++ 讀成十進位字串並截斷到 50,避免題敘未限制輪盤值上限造成溢位。若某張牌在輪盤上完全沒出現,該玩家永遠無法完成。否則給定上一張出牌回合 t,令 t=cycle×K+rem,在位置表二分找第一個大於 rem 的位置;沒有就跳到下一圈第一個位置。

每回合最多出一張,因此必須嚴格晚於 t,不能讓兩張相同的牌共用同回合。盡早打出頂牌不會阻礙後續牌:任何較晚的打法,其剩餘牌能使用的回合也能由較早打法等待取得。逐張選最早可用回合即為全體最早完成時間,各玩家獨立計算。

Step-by-step animation

公開範例:輪盤 1 2 1 3,第二位玩家 3 2 1

回報動畫錯誤
步驟 1 / 3

先出牌 3

輪盤的數字 3 只在位置 4,第一張於第 4 回合出。

1
2
1
3
已用回合
4

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int k, n, m;
    cin >> k >> n >> m;
    vector<vector<int>> pos(50);
    for (int i = 1; i <= k; ++i) {
        string token;
        cin >> token;
        int x = 0;
        for (char digit : token)
            x = min(50, x * 10 + (digit - '0'));
        if (x < 50)
            pos[x].push_back(i);
    }
    for (int player = 0; player < n; ++player) {
        long long t = 0;
        bool possible = true;
        for (int j = 0; j < m; ++j) {
            int x;
            cin >> x;
            if (!possible)
                continue;
            if (pos[x].empty()) {
                possible = false;
                continue;
            }
            long long cycle = t / k;
            int rem = t % k;
            auto it = upper_bound(pos[x].begin(), pos[x].end(), rem);
            if (it == pos[x].end())
                t = (cycle + 1) * k + pos[x][0];
            else
                t = cycle * k + *it;
        }
        cout << (possible ? t : -1) << '\n';
    }
}

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

更多