Cod sursa(job #3373783)

Utilizator indianu_talpa_iuteTisca Catalin indianu_talpa_iute Data 7 noiembrie 2026 21:24:49
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include <fstream>
#include <vector>
#include <algorithm>

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

const int NMAX = 100005;

int n, m;
std::vector<int> graph[NMAX];
int order[NMAX], low[NMAX];
int parent[NMAX], pos[NMAX];
int stk[NMAX], top = 0;
int path[NMAX], depth = 0;
int timer = 0;
std::vector<std::vector<int>> components;

void visit(int node, int from) {
    order[node] = low[node] = ++timer;
    parent[node] = from;
    pos[node] = 0;
    stk[top++] = node;
    path[depth++] = node;
}

void finish(int node, int child) {
    low[node] = std::min(low[node], low[child]);

    if (low[child] < order[node])
        return;

    std::vector<int> component;
    int x;
    do {
        x = stk[--top];
        component.push_back(x);
    } while (x != child);
    component.push_back(node);
    components.push_back(component);
}

void dfs(int start) {
    visit(start, 0);

    while (depth > 0) {
        int node = path[depth - 1];

        if (pos[node] == graph[node].size()) {
            depth--;
            if (depth > 0)
                finish(path[depth - 1], node);
            continue;
        }

        int next = graph[node][pos[node]++];
        if (next == parent[node])
            continue;

        if (order[next])
            low[node] = std::min(low[node], order[next]);
        else
            visit(next, node);
    }
}

int main() {
    fin >> n >> m;

    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 (!order[i]) {
            dfs(i);
            top = 0;
        }
    }

    fout << components.size() << '\n';
    for (auto &component : components) {
        for (int x : component)
            fout << x << ' ';
        fout << '\n';
    }

    return 0;
}