a798中等入度條件與從根可達性

CPE:Is It A Tree? (UVa 615)

連空圖、重邊、環與不連通分量都能辨認。

前往題目練習 →回報教學錯誤每筆 C++ 有序 map/set 時間 O((V+E)log(V+1)),Python 雜湊平均 O(V+E);圖與走訪空間 O(V+E),Python 另有整份輸入緩衝。

解題思路

只把出現在邊兩端的編號當作節點。非空樹必須恰有一個入度為 0 的根,其餘每點入度恰為 1;重複輸入同一條邊也會增加入度,不能先用集合去重。空邊集合依題意直接判為樹。

通過入度檢查後,從根沿有向邊走訪,要求所有節點都可達。單靠根與入度條件仍可能漏掉與根分離的環;加入可達性後,任何可達環都會迫使根有入邊或某點有兩個入邊,因此這些條件充分。0 0 結束一筆,負數對結束整份輸入,案例編號從 1 起。

Step-by-step animation

示意:1→2、1→3

回報動畫錯誤
步驟 1 / 3

統計入度

節點 1、2、3 的入度分別為 0、1、1。

1:0
2:1
3:1
根數
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <map>
#include <vector>
#include <set>
using namespace std;
int main() {
    int u, v, tc = 0;
    map<int, vector<int>> g;
    map<int, int> indeg;
    while (cin >> u >> v && u >= 0 && v >= 0) {
        if (u || v) {
            g[u].push_back(v);
            indeg.try_emplace(u, 0);
            ++indeg[v];
            continue;
        }
        bool ok = true;
        vector<int> roots;
        for (auto [node, d] : indeg) {
            if (!d)
                roots.push_back(node);
            else if (d != 1)
                ok = false;
        }
        if (!indeg.empty()) {
            if (roots.size() != 1)
                ok = false;
            else {
                set<int> seen;
                vector<int> todo{roots[0]};
                while (!todo.empty()) {
                    int x = todo.back();
                    todo.pop_back();
                    if (!seen.insert(x).second)
                        continue;
                    for (int y : g[x])
                        todo.push_back(y);
                }
                if (seen.size() != indeg.size())
                    ok = false;
            }
        }
        cout << "Case " << ++tc << (ok ? " is a tree.\n" : " is not a tree.\n");
        g.clear();
        indeg.clear();
    }
}

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

更多