Cod sursa(job #2870852)

Utilizator Cosmin2004_InfoMoldoveanu Cosmin Cosmin2004_Info Data 12 martie 2022 16:58:54
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>

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

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

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(!d[i])
        dfs(i, 0);
    fout << bcc.size() << "\n";
    for(auto& comp : bcc) {
        for(int x : comp)
            fout << x << " ";
        fout << "\n";
    }
    return 0;
}