a338困難可完成性檢查引導字典序貪心

TOI 2026/06 潛力組:BABA

必須用完全部字母,逐位選出仍可完成的最大字元。

前往題目練習 →回報教學錯誤字母種類固定為 3,時間 O(a+b+c),空間 O(a+b+c) 儲存輸出;容量乘積可達 3×10^10,C++ 用 long long。

解題思路

只挑目前能接的最大字母可能把大量 A 留到最後而無法排完。設剩餘字母數為 cnt,已輸出的尾端字母為 last、連續數為 run。對任何字母 x,其他字母數為 others,它們最多隔出 others+1 個槽,每槽可放 k 個 x;若 x=last,第一槽還要扣掉 run 的已用容量。因此必要條件是 cnt[x]≤k(others+1)−(x=last?run:0)。

此條件也充分。設剩餘總數為 t;若某字母 y 滿足 cnt[y]>k(t−cnt[y]),下一位不能選其他字母,因為那會少掉一個分隔者而使 y 容量不足。這種字母至多一種,因為 k≥1 時它的數量嚴格超過 t/2。選 y 後自身容量條件仍成立;若 y 正是尾端且已連續 k 個,原本容量條件就會禁止上述嚴格不等式,所以不會被迫違規。若沒有這種字母,任選目前連續數允許的字母都保留全部容量條件。每次能少用一個字母並維持條件,歸納到空字串,證明存在合法完成方式。

每一位依 C、B、A 嘗試,暫扣字母後檢查三個不等式,選第一個仍有合法後綴者。因為可完成性判準既必要又充分,這只排除不可能完成的前綴;在與任何其他合法排列的第一個不同位置,選到的字母必定最大。

Step-by-step animation

小例 a=3,b=1,c=1,k=1

回報動畫錯誤
步驟 1 / 3

不能先放 C

放 C 後剩 A=3,B=1,A 的槽只有兩個,容量 2<3。

嘗試 C
剩 A:3
剩 B:1
可完成
否

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <array>
#include <string>
using namespace std;
int main() {
    array<long long, 3> cnt;
    long long k;
    cin >> cnt[0] >> cnt[1] >> cnt[2] >> k;
    auto feasible = [&](int last, long long run) {
        long long total = cnt[0] + cnt[1] + cnt[2];
        for (int x = 0; x < 3; x++)
            if (cnt[x] > k * (total - cnt[x] + 1) - (x == last ? run : 0))
                return false;
        return true;
    };
    if (!feasible(-1, 0)) {
        cout << "No Solution\n";
        return 0;
    }
    int last = -1;
    long long run = 0, total = cnt[0] + cnt[1] + cnt[2];
    string out;
    while (total--) {
        for (int x = 2; x >= 0; x--) {
            if (!cnt[x] || (x == last && run == k))
                continue;
            long long nr = (x == last ? run + 1 : 1);
            --cnt[x];
            if (feasible(x, nr)) {
                out += char('A' + x);
                last = x;
                run = nr;
                break;
            }
            ++cnt[x];
        }
    }
    cout << out << '\n';
}

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

更多