Articulation Points

#include<bits/stdc++.h>
#define ll long long

struct ArticulationPoint 
{
    // NOTE:
    //      vertices are ZERO-BASED index
    //      UN-DIRECTIONAL GRAPH
    int n;
    vector< vector<int> > adj;
    vector<int> artpoint;
    int *num;
    int *low;
    int cnt;
    
    void init(int n_) {
        n = n_;
        
        adj.clear();
        adj.resize(n+1);
        
        artpoint.clear();
        
        num = new int[n+1];
        low = new int[n+1];
        for (int i = 0; i <= n; ++i)
            num[i] = low[i] = -1;
            
        cnt = 0;
    }
    
    void addEdge(int u, int v) {
        adj[u].push_back(v);
        adj[v].push_back(u);
    }
    
    void dfs_artpoint(int u, int pa) {
        num[u] = low[u] = ++cnt;
        int child = 0;
        bool isArtPoint = false;
        
        for (int v : adj[u]) {
            if (v == pa)
                continue;
            
            if (num[v] < 0) {
                dfs_artpoint(v, u);
                low[u] = min(low[u], low[v]);
                ++child;
                
                if (pa != -1 && num[u] <= low[v])
                    isArtPoint = true;
            }
            else {
                low[u] = min(low[u], num[v]);
            }               
        }
        
        if (pa == -1 && child >= 2) {
            isArtPoint = true;
        }
        
        if (isArtPoint)
            artpoint.push_back(u);
        
    }
    
    vector<int> findArtPoint() {
        for (int i = 0; i < n; ++i)
            if (num[i] < 0)
                dfs_artpoint(i, -1);
        
        return artpoint;
    }
    
};

Leave a Reply