Cod sursa(job #3296706)

Utilizator AlexPlesescuAlexPlesescu AlexPlesescu Data 15 mai 2025 19:23:56
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <bits/stdc++.h>

using namespace std;
#define pb push_back
const int N = 1e5 + 5;

int n, m, timer, nr, low[N], tin[N], used[N];
vector<int> g[N], bcc[N];
stack<int> nodes;

void get_bcc(int node, int vec) {
    ++nr;
    while (!nodes.empty() && nodes.top() != vec) {
        bcc[nr].push_back(nodes.top());
        nodes.pop();
    }
    bcc[nr].push_back(nodes.top());
    nodes.pop();
    bcc[nr].push_back(node);
}

void dfs(int node, int p = -1) {
    used[node] = 1;
    low[node] = tin[node] = ++timer;
    nodes.push(node);
    for (auto it: g[node]) {
        if (it == p)
            continue;
        if (used[it]) {
            low[node] = min(low[node], tin[it]);
        } else {
            dfs(it, node);
            low[node] = min(low[node], low[it]);
            if (low[it] >= tin[node]) {
                get_bcc(node, it);
            }
        }
    }
}

int main() {
    cin.tie(nullptr)->sync_with_stdio(false);
    freopen("biconex.in", "r", stdin);
    freopen("biconex.out", "w", stdout);
    cin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int u, v;
        cin >> u >> v;
        g[u].pb(v);
        g[v].pb(u);
    }
    for (int i = 1; i <= n; i++) {
        if (!used[i]) {
            dfs(i);
        }
    }
    cout << nr << '\n';
    for (int i = 1; i <= nr; i++) {
        for (auto it: bcc[i]) {
            cout << it << ' ';
        }
        cout << '\n';
    }
    return 0;
}