Cod sursa(job #2798570)

Utilizator truscalucaLuca Trusca truscaluca Data 11 noiembrie 2021 16:13:51
Problema Componente biconexe Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <iostream>
#include <list>
#include <stack>

using namespace std;

const int nMax = 100005;
list<int> a[nMax];
list<list<int>> comps;
stack<int> s;
int n, m, low[nMax];

void add(int x, int y) {
    list<int> comp;
    while (s.top() != y) {
        comp.push_back(s.top());
        s.pop();
    }
    comp.push_back(y);
    comp.push_back(x);
    s.pop();
    comps.push_back(comp);
}

void dfs(int x, int prev, int id) {
    low[x] = id;
    s.push(x);

    for (auto y: a[x]) {
        if (y == prev) continue;

        if (!low[y]) {
            dfs(y, x, id + 1);
            low[x] = min(low[x], low[y]);

            if (low[y] >= id) {
                add(x, y);
            }
        } else {
            low[x] = min(low[x], low[y]);
        }
    }
}

int main() {
    freopen("biconex.in", "r", stdin);
    freopen("biconex.out", "w", stdout);

    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y;
        cin >> x >> y;
        a[x].push_back(y);
        a[y].push_back(x);
    }

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

    cout << comps.size() << "\n";
    for (auto &comp: comps) {
        for (auto x: comp) {
            cout << x << " ";
        }
        cout << "\n";
    }

    return 0;
}