a284困難割點・low-link・稠密圖位元鄰接表

TOI 2019/04 潛力組:關鍵星

一次 DFS 找出移除後會切斷星圖的頂點,按編號遞減輸出。

前往題目練習 →回報教學錯誤C++ 時間 O(E+V²)、位元矩陣空間 O(V²/64+V)。Python 設 W=ceil(V/機器字位數),讀圖 O(EW)、搜尋 O(VW log V),空間 O(VW);大整數位元運算不是 O(1)。V=10000 的純矩陣約 12.5 MB。

解題思路

DFS 記錄 tin 與 low。非根頂點 u 若有樹子節點 v 滿足 low[v]≥tin[u],則 v 子樹沒有不經 u 回到 u 祖先的路,移除 u 會斷開星圖。根沒有祖先,必須另外判斷:DFS 樹子節點至少兩個才是割點。只有一顆或兩顆星時也遵守這些規則。

V≤10000,但 E 可達 V(V−1)/2,不能在 Python 把整份輸入 split 後儲存數千萬個端點整數。程式逐行讀取,使用每列 V 位的鄰接矩陣。C++ 迭代 DFS 掃描每列;Python 以大整數找尚未造訪鄰居,進入節點時,利用『已造訪頂點前綴遮罩』二分出最早的非父鄰居作為回邊 low 初值。無向 DFS 沒有跨分支邊,因此後來才被造訪的鄰居只能是後代,其 tin 更大,不會改善 low;子樹完成時仍照常向父節點傳遞 low。

Step-by-step animation

範例三角形接到 3,3 再接 4、5

回報動畫錯誤
步驟 1 / 3

三角形回邊

以 0 為根,0→1→2 後,2 可回到 0,所以 low[2]=0。

0:tin0
1:tin1
2:tin2/low0
1 是割點
否

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <cstdint>
#include <algorithm>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    long long m;
    cin >> n >> m;
    int words = (n + 63) / 64;
    vector<vector<uint64_t>> g(n, vector<uint64_t>(words));
    for (long long i = 0; i < m; ++i) {
        int a, b;
        cin >> a >> b;
        g[a][b / 64] |= 1ULL << (b % 64);
        g[b][a / 64] |= 1ULL << (a % 64);
    }
    vector<int> tin(n, -1), low(n), parent(n, -1), cursor(n), children(n), stack;
    vector<bool> cut(n, false);
    int timer = 0;
    for (int root = 0; root < n; ++root)
        if (tin[root] < 0) {
            stack.push_back(root);
            tin[root] = low[root] = timer++;
            while (!stack.empty()) {
                int u = stack.back();
                while (cursor[u] < n && !(g[u][cursor[u] / 64] >> (cursor[u] % 64) & 1ULL))
                    ++cursor[u];
                if (cursor[u] < n) {
                    int v = cursor[u]++;
                    if (v == parent[u])
                        continue;
                    if (tin[v] < 0) {
                        parent[v] = u;
                        ++children[u];
                        tin[v] = low[v] = timer++;
                        stack.push_back(v);
                    } else
                        low[u] = min(low[u], tin[v]);
                } else {
                    stack.pop_back();
                    int p = parent[u];
                    if (p >= 0) {
                        low[p] = min(low[p], low[u]);
                        if (parent[p] >= 0 && low[u] >= tin[p])
                            cut[p] = true;
                    } else
                        cut[u] = children[u] > 1;
                }
            }
        }
    bool any = false;
    for (int u = n - 1; u >= 0; --u)
        if (cut[u]) {
            if (any)
                cout << ' ';
            cout << u;
            any = true;
        }
    if (!any)
        cout << "FAIL";
    cout << '\n';
}

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

更多