Cod sursa(job #3372720)

Utilizator Vlad_prisVlad Prismareanu Vlad_pris Data 4 noiembrie 2026 19:31:39
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

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

vector<vector<int>> Adj;
vector<int> disc, low, stk;
vector<vector<int>> components;
int timer = 0;

void dfs(int node, int parent) {
    disc[node] = low[node] = ++timer;
    stk.push_back(node);

    for (int neighbor : Adj[node]) {
        if (neighbor == parent) continue;

        if (disc[neighbor] != 0) {
            low[node] = min(low[node], disc[neighbor]);
        } else {
            dfs(neighbor, node);
            low[node] = min(low[node], low[neighbor]);

            if (low[neighbor] >= disc[node]) {
                vector<int> comp;
                while (stk.back() != neighbor) {
                    comp.push_back(stk.back());
                    stk.pop_back();
                }
                comp.push_back(neighbor);
                stk.pop_back();
                comp.push_back(node);
                components.push_back(comp);
            }
        }
    }
}

int main() {
    int n, m;
    fin >> n >> m;
    Adj.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;
        Adj[x].push_back(y);
        Adj[y].push_back(x);
    }

    for (int i = 1; i <= n; i++)
        if (disc[i] == 0)
            dfs(i, 0);

    fout << components.size() << "\n";
    for (auto& comp : components) {
        for (int node : comp)
            fout << node << " ";
        fout << "\n";
    }
    return 0;
}