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

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

洛谷__P8436 【模板】边双连通分量

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


题目描述:

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


边双连通分量:

一张不存在桥无向的连通图


代码:

#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 72340172838076673
#define int long long
#define endl '\n'
#define F first
#define S second
#define  mst(a,x) memset(a,x,sizeof (a))
using namespace std;
typedef pair<int, int> pii;

const int N = 500086, M = 2000086 * 2, mod = 998244353;

int n, m;
int h[N], ne[M], e[M], idx;
int dfn[N], low[N], ti;
stack<int> st;
vector<int> id[N];
int cnt = 0;

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

void tarjan(int u, int from) {

    dfn[u] = low[u] = ++ti;
    st.push(u);
    
    for (int i = h[u]; ~i; i = ne[i]) {
        int j = e[i];
        if (!dfn[j]) {
            tarjan(j, i);
            low[u] = min(low[u], low[j]);
        } else if (i != (from ^ 1)) low[u] = min(low[u], dfn[j]);
    }
    
    if (dfn[u] == low[u]) {
        int y;
        cnt++;
        do {
            y = st.top();
            st.pop();
            id[cnt].push_back(y);
        } while (u != y);
    }
    
}

void solve() {

    mst(h, -1);
    cin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int a, b;
        cin >> a >> b;
        if (a == b) continue;
        add(a, b), add(b, a);
    }
    
    for (int i = 1; i <= n; i++) {
        if (!dfn[i]) tarjan(i, -1);
    }
    
    cout << cnt << endl;
    for (int i = 1; i <= cnt; 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-28 00:08  wwjjw  阅读(17)  评论(0)    收藏  举报