递归 Tarjan 数出几个分量

👁️ 1 人浏览 💬 0 人评论 ❤️ 添加收藏

还是那七个点,这次把 5 → 3 那条边加回来,于是图里有了环。

运行下面这段程序:

#include <algorithm>
#include <climits>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <string>
#include <utility>
#include <vector>
using namespace std;

using Edges = vector<pair<int, int>>;
const int N = 7;
// 七个构建任务,(a, b) 表示 a 做完才能做 b
const Edges DEP = {{0, 1}, {0, 2}, {1, 3}, {2, 3}, {3, 4}, {4, 5}, {4, 6}};
// 同一张图再加一条 5 → 3,于是有了环
const Edges G = {{0, 1}, {0, 2}, {1, 3}, {2, 3}, {3, 4}, {4, 5}, {5, 3}, {4, 6}};

vector<vector<int>> build(const Edges& edges, int n = N) {
    vector<vector<int>> g(n);
    for (auto [a, b] : edges) g[a].push_back(b);
    for (auto& adj : g) sort(adj.begin(), adj.end());
    return g;
}

// 递归版 Tarjan:dfn 是访问时间戳,low 是能回溯到的最早时间戳
int timer_ = 0, scc_cnt = 0;
vector<int> dfn, low, onst, stk, sizes;

void tarjan(const vector<vector<int>>& g, int u) {
    dfn[u] = low[u] = ++timer_;
    stk.push_back(u);
    onst[u] = 1;
    for (int v : g[u]) {
        if (!dfn[v]) {
            tarjan(g, v);
            low[u] = min(low[u], low[v]);
        } else if (onst[v]) {
            low[u] = min(low[u], dfn[v]);
        }
    }
    if (low[u] == dfn[u]) {
        int sz = 0;
        while (true) {
            int x = stk.back();
            stk.pop_back();
            onst[x] = 0;
            sz++;
            if (x == u) break;
        }
        sizes.push_back(sz);
        scc_cnt++;
    }
}

int main() {
    vector<vector<int>> g = build(G);
    dfn.assign(N, 0);
    low.assign(N, 0);
    onst.assign(N, 0);
    for (int u = 0; u < N; u++) {
        if (!dfn[u]) tarjan(g, u);
    }
    cout << scc_cnt << "/" << *max_element(sizes.begin(), sizes.end()) << endl;
}

(本题用 g++ -std=c++17 -O0 编译。)

提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论