a269困難高度 DAG・最長路徑計數・大整數

TOI 2020/12 潛力組:空中鋼索

只累加達到最長長度的路線數,完整輸出不取餘數。

前往題目練習 →回報教學錯誤設 D 為答案最大十進位位數(O(N))。時間 O(N log N + M·D),空間 O(N + M + N·D);分塊大整數的加法不能當作 O(1)。

解題思路

將每條鋼索從高基地指向低基地,相同高度的鋼索直接忽略。沿路高度嚴格下降,所以不會有環。依高度由高到低處理,就是一個合法拓樸順序;每個節點處理前,所有可進入它的較高節點都已處理。

令 length[v] 為 1 到 v 的最多鋼索數,ways[v] 為達到該長度的路線數。從可達的 u 到 v,若 length[u]+1 較大便覆蓋長度與計數,相等才累加。不可達初值為 −1、計數為 0;起點是長度 0、計數 1。路線數可能呈指數成長,Python 用任意精度整數,C++ 以十進位分塊實作加法。

Step-by-step animation

範例的最長長度與路線數

回報動畫錯誤
步驟 1 / 3

由基地 1 出發

1→2、1→3 都是一條鋼索;直達 5 的長度也先設為 1。

1:0/1
2:1/1
3:1/1
4:−1/0
5:1/1
格式
長度/計數

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <iomanip>
using namespace std;
struct Big {
    static const int base = 1000000000;
    vector<int> d;
    Big(int x = 0) {
        if (x)
            d.push_back(x);
    }
    void add(const Big &b) {
        d.resize(max(d.size(), b.d.size()), 0);
        long long carry = 0;
        for (size_t i = 0; i < d.size(); ++i) {
            long long sum = d[i] + carry + (i < b.d.size() ? b.d[i] : 0);
            d[i] = int(sum % base);
            carry = sum / base;
        }
        if (carry)
            d.push_back(int(carry));
    }
    void print() const {
        if (d.empty()) {
            cout << 0;
            return;
        }
        cout << d.back();
        for (int i = int(d.size()) - 2; i >= 0; --i)
            cout << setw(9) << setfill('0') << d[i];
    }
};
int main() {
    int n, m;
    cin >> n >> m;
    vector<long long> h(n);
    for (auto &x : h)
        cin >> x;
    vector<vector<int>> g(n);
    for (int i = 0, a, b; i < m; ++i) {
        cin >> a >> b;
        --a;
        --b;
        if (h[a] < h[b])
            swap(a, b);
        if (h[a] > h[b])
            g[a].push_back(b);
    }
    vector<int> order(n), length(n, -1);
    iota(order.begin(), order.end(), 0);
    sort(order.begin(), order.end(), [&](int a, int b) { return h[a] > h[b]; });
    vector<Big> ways(n);
    length[0] = 0;
    ways[0] = Big(1);
    for (int u : order)
        if (length[u] >= 0)
            for (int v : g[u]) {
                int candidate = length[u] + 1;
                if (candidate > length[v]) {
                    length[v] = candidate;
                    ways[v] = ways[u];
                } else if (candidate == length[v])
                    ways[v].add(ways[u]);
            }
    ways[n - 1].print();
    cout << '\n';
}

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

更多