Cod sursa(job #3372475)

Utilizator iLaurianLaurian Iacob iLaurian Data 3 noiembrie 2026 23:47:16
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <algorithm>
#include <fstream>
#include <vector>

std::ifstream f ("biconex.in");
std::ofstream g ("biconex.out");

const int MAXN = 100005;
std::vector<int> adj[MAXN];
int tin[MAXN], low[MAXN];
int timer = 0;

std::vector<std::pair<int,int>> st;
std::vector<std::vector<int>> bccs;

void dfs(int u, int p) {
    tin[u] = low[u] = ++timer;
    for (int v : adj[u]) {
        if (v == p) continue;
        if (tin[v]) {
            low[u] = std::min(low[u], tin[v]);
            if (tin[u] > tin[v]) {
                st.push_back({u, v});
            }
        } else {
            st.push_back({u, v});
            dfs(v, u);
            low[u] = std::min(low[u], low[v]);
            if (tin[u] <= low[v]) {
                std::vector<int> comp;
                std::pair<int, int> edge;
                do {
                    edge = st.back();
                    st.pop_back();
                    comp.push_back(edge.first);
                    comp.push_back(edge.second);
                } while (edge != std::make_pair(u,v));

                std::sort(comp.begin(), comp.end());
                comp.erase(std::unique(comp.begin(), comp.end()), comp.end());
                bccs.push_back(comp);
            }
        }
    }
}

int main() {
    int n, m;
    f >> n >> m;
    for (int i = 1; i <= m; i++) {
        int x, y; f >> x >> y;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }

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

    g << bccs.size() << '\n';
    for (auto bcc : bccs) {
        for (auto x : bcc)
            g << x << ' ';
        g << '\n';
    }

    return 0;
}