Cod sursa(job #3374108)

Utilizator mar_parapeanumaria parapeanu mar_parapeanu Data 8 noiembrie 2026 18:04:23
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <fstream>
#include <vector>
#include <algorithm>

std::ifstream fin("biconex.in");
std::ofstream fout("biconex.out");

std::vector<std::vector<int>> graph;
std::vector<int> disc; 
std::vector<int> low;
std::vector<int> stiva;
std::vector<std::vector<int>> componente;
int timp = 0;

void dfs(int u, int parinte) {
    disc[u] = low[u] = ++timp;
    stiva.push_back(u);

    for (int v : graph[u]) {
        if (v == parinte)
            continue;
        if (disc[v] == 0) {
            dfs(v, u);
            low[u] = std::min(low[u], low[v]);
            if (low[v] >= disc[u]) {
                std::vector<int> comp;
                int x;
                do {
                    x = stiva.back();
                    stiva.pop_back();
                    comp.push_back(x);
                } while (x != v);
                comp.push_back(u);
                componente.push_back(comp);
            }
        } else {
            low[u] = std::min(low[u], disc[v]);
        }
    }
}

int main() {
    int n, m;
    fin >> n >> m;
    graph.resize(n + 1);
    disc.assign(n + 1, 0);
    low.assign(n + 1, 0);
    for (int i = 0; i < m; i++) {
        int x, y;
        fin >> x >> y;
        graph[x].push_back(y);
        graph[y].push_back(x);
    }
    for (int i = 1; i <= n; i++) {
        if (disc[i] == 0) {
            dfs(i, 0);
            stiva.pop_back();
        }
    }
    fout << componente.size() << "\n";
    for (const auto &comp : componente) {
        for (int nod : comp)
            fout << nod << " ";
        fout << "\n";
    }
    return 0;
}