Cod sursa(job #3236032)

Utilizator AlexPlesescuAlexPlesescu AlexPlesescu Data 25 iunie 2024 18:57:16
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <bits/stdc++.h>

using namespace std;
#define int long long int
#define pb push_back
#define len(s) (int) s.size()
const int N = 2e5 + 5, mod = 1e9 + 7;

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

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

void dfs(int node, int parent = -1) {
    visited[node] = 1;
    low[node] = d[node] = timer++;
    nodes.push(node);
    int children = 0;
    for (auto to: g[node]) {
        if (to == parent)
            continue;
        if (visited[to]) {
            low[node] = min(low[node], d[to]);
        } else {
            dfs(to, node);
            low[node] = min(low[node], low[to]);
            if (low[to] >= d[node]) {
                get_bcc(node, to);
            }
            ++children;
        }
    }

}

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