--- 这里是 cjiaw 的小窝(●'◡'●) ---

正在玩命加载中......

洛谷__P8435 【模板】点双连通分量

题目链接:P8435 【模板】点双连通分量 - 洛谷


题目描述:

对于一个  个节点  条无向边的图,请输出其点双连通分量的个数,并且输出每个点双连通分量。


点双连通分量:

在一个无向图的点双连通分量中,删除任意一点,剩下的所有点仍然互相连通


代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<bitset>
#include<tuple>
#define inf 9187201950435737471
#define int long long
#define endl '\n'
#define F first
#define S second
using namespace std;
typedef pair<int, int> pii;

const int N = 500010, M = 2000010 * 2;

int n, m, root;
int h[N], ne[M], e[M], idx;
int dfn[N], low[N], ti;
stack<int> st;
int dcnt;
vector<int> id[N];//缩点

void add(int a, int b) {
    e[idx] = b;
    ne[idx] = h[a];
    h[a] = idx++;
}

void tarjan(int u) {

    dfn[u] = low[u] = ++ti;
    
    if (u == root && h[u] == -1) {//单独的点
        dcnt++;
        id[dcnt].push_back(u);
        return;
    }
    
    st.push(u);
    for (int i = h[u]; ~i; i = ne[i]) {
        int j = e[i];
        if (!dfn[j]) {
            tarjan(j);
            low[u] = min(low[u], low[j]);
            
            // 关键判断:如果u是割点,则找到一个点双连通分量
            if (dfn[u] <= low[j]) {//从j出发无法到达u的祖先节点
                int y;
                dcnt++;
                do {
                    y = st.top();
                    st.pop();
                    id[dcnt].push_back(y);
                } while (y != j);
                id[dcnt].push_back(u); // 割点u也属于这个分量
            }
            
        } else low[u] = min(low[u], dfn[j]);
    }
    
}

void solve() {
    memset(h, -1, sizeof h);
    cin >> n >> m;
    while (m--) {
        int a, b;
        cin >> a >> b;
        if (a == b) continue;
        add(a, b), add(b, a);
    }
    
    for (root = 1; root <= n; root++) {
        if (!dfn[root]) tarjan(root);
    }
    
    cout << dcnt << endl;
    for (int i = 1; i <= dcnt; i++) {
        cout << id[i].size() << " ";
        for (auto x : id[i]) cout << x << " ";
        cout << endl;
    }
    
    
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    
    int T = 1;
// cin >> T;
    while (T--) solve();
    
    return 0;
}

 

posted @ 2025-10-27 22:33  wwjjw  阅读(13)  评论(0)    收藏  举报