Cod sursa(job #3374374)

Utilizator CondoracheTudorCondorache Tudor CondoracheTudor Data 8 noiembrie 2026 23:33:29
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> adj[100005];
int idx[100005], low[100005];
vector<int> st;
vector<vector<int>> bcc;
int timer;

void dfs(int u, int p) {
    idx[u] = low[u] = ++timer;
    st.push_back(u);

    for (int v : adj[u]) {
        if (v == p) continue;
        if (idx[v]) {
            low[u] = min(low[u], idx[v]);
        } else {
            dfs(v, u);
            low[u] = min(low[u], low[v]);
            if (low[v] >= idx[u]) {
                vector<int> comp;
                comp.push_back(u);
                while (true) {
                    int node = st.back();
                    st.pop_back();
                    comp.push_back(node);
                    if (node == v) break;
                }
                bcc.push_back(comp);
            }
        }
    }
}

int main() {
    ifstream fin("biconex.in");
    ofstream fout("biconex.out");

    int n, m;
    fin >> n >> m;

    for (int i = 0; i < m; ++i) {
        int u, v;
        fin >> u >> v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }

    for (int i = 1; i <= n; ++i) {
        if (!idx[i]) {
            dfs(i, 0);
        }
    }

    fout << bcc.size() << "\n";
    for (const auto& comp : bcc) {
        for (int node : comp) {
            fout << node << " ";
        }
        fout << "\n";
    }

    return 0;
}