graph theory - tarjan's algorithm implementation

reference:

  1. https://codeforces.com/blog/entry/71146
  2. https://www.geeksforgeeks.org/articulation-points-or-cut-vertices-in-a-graph/

articulation points


#include 
#include 

using namespace std;


int ap_dfs(vector> &adj, int u, int p, vector &dfn, vector &low, int &time) {
    dfn[u] = low[u] = time++;
    int children = 0;
    for (auto v : adj[u]) {
        if (v == p) {
            continue;
        }

        if (dfn[v] == -1) {
            ap_dfs(adj, v, u, dfn, low, time);
            low[u] = min(low[u], low[v]);
            if (p != -1 && dfn[u] <= low[v]) {
                cout << u << endl; // will be outputed more than once
            }
            ++children;
        } else {
            low[u] = min(low[u], dfn[v]);
        }
    }

    return children;
}

void ap(int n, vector> &edges) {
    vector dfn(n, -1);
    vector low(n, -1);
    vector> adj(n);
    for (auto e : edges) {
        adj[e[0]].push_back(e[1]);
        adj[e[1]].push_back(e[0]);
    }
    
    int time = 0;
    for (int i = 0; i < n; ++i) {
        if (dfn[i] == -1) {
            int children = ap_dfs(adj, i, -1, dfn, low, time);
            if (children > 1) {
                cout << i << endl;
            }
        }
    }
}


int main() {

    vector> edges{
        {1, 2},
        {2, 3},
        {3, 1},
        {3, 4},
        {1, 5},
    };

    ap(6, edges);

    return 0;
}

bridges

change if (p != -1 && dfn[u] <= low[v]) to if (dfn[u] <= low[v]) will be done

你可能感兴趣的:(graph theory - tarjan's algorithm implementation)