Cod sursa(job #3294634)

Utilizator _andr31Rusanescu Andrei-Marian _andr31 Data 26 aprilie 2025 16:42:58
Problema Componente biconexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <bits/stdc++.h>
using namespace std;

int main() {
    ifstream fin("biconex.in");
    ofstream fout("biconex.in");

    int n, m;
    fin >> n >> m;

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

    vector<vector<int>> bccs;
    vector<int> low_link(n + 1, INT_MAX), index(n + 1, -1), parent(n + 1, -1);
    int t = 0;
    stack<pair<int, int>> st;
    unordered_set<int> bc;

    function<void(int)> dfs = [&](int nod) -> void {
        low_link[nod] = index[nod] = ++t;
        for (int vec : adj[nod]) {
            if (parent[vec] == -1) {
                parent[vec] = nod;
                st.emplace(nod, vec);
                dfs(vec);
                low_link[nod] = min(low_link[nod], low_link[vec]);

                if (low_link[vec] >= index[nod]) {
                    while (!st.empty()) {
                        auto [x, y] = st.top(); st.pop();
                        bc.insert(x);
                        bc.insert(y);
                        if (x == nod && y == vec) break;
                    }
                    bccs.emplace_back(bc.begin(), bc.end());
                    bc.clear();
                }
            } else if (vec != parent[nod]) {
                low_link[nod] = min(low_link[nod], index[vec]);
            }
        }
    };

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

    fout << bccs.size() << '\n';
    for (auto& bcc : bccs) {
        for (int val : bcc) {
            fout << val << ' ';
        }
        fout << '\n';
    }

    return 0;
}