Cod sursa(job #2851594)

Utilizator Cosmin2004_InfoMoldoveanu Cosmin Cosmin2004_Info Data 18 februarie 2022 20:51:40
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <bits/stdc++.h>

using namespace std;
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 v) {
    low[u] = d[u] = d[v] + 1;
    st.push(u);
    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(low[v] == d[u]) {
                bcc.push_back({u});
                while(st.top() != v) {
                    bcc.back().push_back(st.top());
                    st.pop();
                }
                bcc.back().push_back(v);
                st.pop();
            }
        }
    }
}

int main()
{
    #ifndef HOME
    ifstream cin("biconex.in");
    ofstream cout("biconex.out");
    #endif // HOME
    int n, m, u, v;
    cin >> n >> m;
    for(int i = 1; i <= m; i++)
        cin >> 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);
    cout << bcc.size() << "\n";
    for(auto& comp : bcc) {
        for(int x : comp)
            cout << x << " ";
        cout << "\n";
    }
    return 0;
}