a324困難DAG 路線計數・拓樸序與任意精度加法

TOI 2019/05 潛力組:巨額獎金

在沒有答案位元上界的題目中,精確計算起點到終點的路線數。

前往題目練習 →回報教學錯誤令 B 為中間計數的最大二進位長度,時間 O(N+E+EB) 位元量級,儲存圖 O(N+E),大數最壞 O(NB) 位元;十進位輸出另有轉換成本。N≤10⁶,使用顯式拓樸佇列,無深遞迴。

解題思路

不會重訪階段的保證讓可行遊戲圖可用 DAG 模型處理。令 ways[v] 為從 0 走到 v 的路線數,ways[0]=1;拓樸排序取出 u 後,對每條 u→v 執行 ways[v]+=ways[u]。當 v 的入度歸零時,所有前驅已處理,因此 ways[v] 已完整,計數不會少算或重複。階段編號不保證就是拓樸序,不能直接由小編號算到大編號。

原題沒有取模或答案上界,故 Python 使用內建任意精度整數,C++ 實作以 10⁹ 為基底的非負大整數加法。處理完節點的計數可釋放,減少長鏈留下大量大數的空間。事件數限制中的 S 未定義,所以以下複雜度保留 E,不能把 E≤2N 當作已確認規格;大數運算也不能算作固定時間。

Step-by-step animation

較小示例:0→1、0→2、1→2、1→3、2→3

回報動畫錯誤
步驟 1 / 3

處理起點

空路線給 ways[0]=1,沿兩條邊傳到 1、2。

0:1
1:1
2:1
3:0
下個拓樸節點
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <cstdint>
#include <iomanip>
using namespace std;
struct Big {
    static constexpr uint64_t base = 1000000000;
    vector<uint32_t> d;
    void add(const Big &other) {
        if (d.size() < other.d.size())
            d.resize(other.d.size());
        uint64_t carry = 0;
        for (size_t i = 0; i < d.size(); ++i) {
            uint64_t s = uint64_t(d[i]) + carry + (i < other.d.size() ? other.d[i] : 0);
            d[i] = s % base;
            carry = s / base;
        }
        if (carry)
            d.push_back(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() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, e;
    cin >> n >> e;
    vector<int> head(n, -1), to(e), next(e), degree(n);
    for (int k = 0; k < e; ++k) {
        int u, v;
        cin >> u >> v;
        to[k] = v;
        next[k] = head[u];
        head[u] = k;
        ++degree[v];
    }
    vector<int> queue;
    queue.reserve(n);
    for (int i = 0; i < n; ++i)
        if (!degree[i])
            queue.push_back(i);
    vector<Big> ways(n);
    ways[0].d.push_back(1);
    for (size_t front = 0; front < queue.size(); ++front) {
        int u = queue[front];
        for (int k = head[u]; k != -1; k = next[k]) {
            int v = to[k];
            ways[v].add(ways[u]);
            if (--degree[v] == 0)
                queue.push_back(v);
        }
        if (u != n - 1)
            vector<uint32_t>().swap(ways[u].d);
    }
    ways[n - 1].print();
    cout << '\n';
}

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

更多