Cod sursa(job #3212927)

Utilizator maiaauUngureanu Maia maiaau Data 12 martie 2024 12:06:32
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int,int>;
#define pb push_back
#define fi first
#define se second

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

const int N = 1e5+3;

int n, k;
stack<pii> stk;
vector<int> h, lw;
vector<vector<int>> e, comp;

void read(), dfs(int, int), addcomp(int,int);

int main()
{
    fin.tie(0), fout.tie(0), ios_base::sync_with_stdio(0);
    read();
    dfs(1, 0);
    fout << k << '\n';
    for (int i = 0; i < k; i++){
        for (auto it: comp[i]) fout << it << ' ';
        fout << '\n';
    }

    return 0;
}

void read(){
    int m; fin >> n >> m;
    e.resize(n+3); h.resize(n+3), lw.resize(n+3);
    while (m--) {
        int a, b; fin >> a >> b;
        e[a].pb(b); e[b].pb(a);
    }
}

void dfs(int nod, int t){
    h[nod] = h[t] + 1;
    lw[nod] = h[nod];
    for (auto it: e[nod]){
        if (it == t) continue;
        if (h[it]) {lw[nod] = min(h[it], lw[nod]); continue;}

        stk.push({nod, it});
        dfs(it, nod);
        lw[nod] = min(lw[nod], lw[it]);
        if (lw[it] >= h[nod])
            addcomp(nod, it);
    }
}

void addcomp(int from, int to) {
    comp.pb({});
    unordered_set<int> s;
    int x, y; 
    do {
        tie(x, y) = stk.top(); stk.pop();
        s.insert(x); s.insert(y);
    } while (x != from || y != to);
    for (auto it: s) comp[k].pb(it);
    k++;
}