b063困難

102 高雄市資訊學科能力競賽複賽(2013)|卡片遊戲

先匹配最長合法前綴,再在最右可行位置提升。

解題思路

字典序最小且大於T的S,必盡可能晚才首次大於T。以used標記已匹配前綴的卡片,另維護尚未使用的最大卡maxFree;只要maxFree>T[i],當前位置就是可提升候選,持續保留最右者。

若T[i]未用,先標記它以延伸相等前綴,並把maxFree向左移到下一張未用卡;遇到重複則停止。maxFree全程只減小,所有移動總共至多M次。

回復候選位置起暫取出的卡片,從T[pivot]+1向上找第一張未用卡作首次提升。再從1向上掃描,依序取最小未用卡填滿尾段。每支掃描指標只前進,整個方案O(N+M),不需順序統計樹。

每組時間O(N+M),used為O(M)位元組、答案O(N);Python整份read().split()另用O(總輸入)儲存。

Step-by-step animation

最右可提升前綴與線性可用卡片掃描|N=3、M=4、T=2,2,1

回報動畫錯誤
步驟 1 / 3

匹配

N=3,M=4,T=2,2,1;第一位2可匹配並取走卡2。

2
?
?
已用
2

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int Q;
    cin >> Q;
    while (Q--) {
        int n, m;
        cin >> n >> m;
        vector<int> t(n);
        for (int &x : t)
            cin >> x;
        vector<unsigned char> used(m + 1);
        int largest = m, pivot = -1, matched = 0;
        for (int i = 0; i < n; i++) {
            if (largest > t[i])
                pivot = i;
            if (used[t[i]])
                break;
            used[t[i]] = 1;
            matched++;
            while (largest && used[largest])
                largest--;
        }
        for (int i = pivot; i < matched; i++)
            used[t[i]] = 0;
        vector<int> ans(t.begin(), t.begin() + pivot);
        int x = t[pivot] + 1;
        while (used[x])
            x++;
        ans.push_back(x);
        used[x] = 1;
        int next = 1;
        while ((int)ans.size() < n) {
            while (used[next])
                next++;
            ans.push_back(next);
            used[next] = 1;
            next++;
        }
        for (int i = 0; i < n; i++)
            cout << (i ? " " : "") << ans[i];
        cout << "\n";
    }
}

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

更多