b042困難

111 全國資訊學科能力競賽(2022)|算樹 (tree)

由度數決定Prüfer每個編號的出現次數。

解題思路

Prüfer序列中編號i恰出現degree[i]−1次。反過來任何具有這些頻率的序列都對應合法標號樹,因此問題是多重集合的第k小排列。

剩餘長度r、頻率c[i]時,排列總數T=r!/∏c[i]!。若下一位選i,其分支數恰為T·c[i]/r,為整數。

從小編號逐一扣排名,找到k落入的分支後更新T與頻率。用任意精度計算真實總數,不能先把T截在k,否則除法會失真。

時間 O(n²)次整數檢查與O(n)次大整數更新,最大數字O(n log n)位元;頻率O(n),Python讀入O(n)。

Step-by-step animation

多重集合排列的排名反解|n=4,度數2,2,1,1,序列頻率為1,1,0,0。

回報動畫錯誤
步驟 1 / 3

頻率

n=4,度數2,2,1,1,序列頻率為1,1,0,0。

1:1
2:1
總數
2

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::cpp_int;
int main() {
    int n;
    long long k;
    cin >> n >> k;
    vector<int> c(n);
    vector<cpp_int> f(n + 1);
    f[0] = 1;
    for (int i = 1; i <= n; i++)
        f[i] = f[i - 1] * i;
    cpp_int t = f[n - 2];
    for (int &i : c) {
        cin >> i;
        i--;
        t /= f[i];
    }
    if (t < k) {
        cout << -1 << "\n";
        return 0;
    }
    for (int r = n - 2; r; r--)
        for (int i = 0; i < n; i++)
            if (c[i]) {
                cpp_int b = t * c[i] / r;
                if (b < k)
                    k -= b.convert_to<long long>();
                else {
                    cout << i + 1 << "\n";
                    t = b;
                    c[i]--;
                    break;
                }
            }
}

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

更多