Cod sursa(job #2836782)

Utilizator Cosmin2004_InfoMoldoveanu Cosmin Cosmin2004_Info Data 20 ianuarie 2022 21:21:57
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>

using namespace std;
#ifdef HOME
ifstream fin("ciorna.in");
ofstream fout("ciorna.out");
#else
ifstream fin("biconex.in");
ofstream fout("biconex.out");
#endif
const int N = 1e5;
vector <vector <int>> bcc;
vector <int> g[N + 5];
stack <int> st;
int low[N + 5], depth[N + 5];

void dfs(int u, int d) {
    st.push(u);
    low[u] = depth[u] = d;
    for(int v : g[u]) {
        if(depth[v]) low[u] = min(low[u], depth[v]);
        else {
            dfs(v, d + 1);
            low[u] = min(low[u], low[v]);
            if(low[v] == depth[u]) {
                bcc.push_back({u});
                int x;
                do {
                    x = st.top();
                    st.pop();
                    bcc.back().push_back(x);
                } while(x != v);
            }
        }
    }
}

int main()
{
    int n, m, u, v;
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
        fin >> u >> v,
        g[u].push_back(v),
        g[v].push_back(u);
    for(int i = 1; i <= n; i++) if(!depth[i])
        dfs(i, 0);
    fout << bcc.size() << "\n";
    for(auto& v : bcc) {
        for(int u : v)
            fout << u << " ";
        fout << "\n";
    }
    return 0;
}