Cod sursa(job #3374540)

Utilizator MihaiDBRDobrin Mihai MihaiDBR Data 9 noiembrie 2026 01:56:20
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

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

int n, m, timp;
vector<int> v[100005];
int niv[100005], low[100005];
stack<int> st;
vector<vector<int>> comp;

void componenta(int x, int y) {
    comp.push_back(vector<int>());
    int z;
    do {
        z = st.top();
        st.pop();
        comp.back().push_back(z);
    } while (z != y);
    comp.back().push_back(x);
}

void dfs(int x) {
    niv[x] = low[x] = ++timp;
    st.push(x);
    for (int y : v[x]) {
        if (niv[y] == 0) {
            dfs(y);
            low[x] = min(low[x], low[y]);
            if (low[y] >= niv[x])
                componenta(x, y);
        } else
            low[x] = min(low[x], niv[y]);
    }
}

int main() {
    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y;
        fin >> x >> y;
        v[x].push_back(y);
        v[y].push_back(x);
    }
    for (int i = 1; i <= n; i++)
        if (niv[i] == 0) {
            dfs(i);
            st.pop();
        }
    fout << comp.size() << '\n';
    for (vector<int> &c : comp) {
        for (int x : c)
            fout << x << ' ';
        fout << '\n';
    }
    return 0;
}