Cod sursa(job #2668203)

Utilizator anayepAna-Maria Ungureanu anayep Data 4 noiembrie 2020 17:17:49
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

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

stack<pair<int, int> > stk;
int n, m, v[100005];
vector<int> g[100005];
vector<vector<int> > comp;
int nivel[100005], low[100005]; ///low[i] = nivelul minim la care se poate ajunge din subarborele nodului i
/// doar prin muchiile de intoarcere


void citire() {
    fin >> n >> m;
    while(m--) {
        int x, y;
        fin >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }
}

void add(int x, int y) {
    vector<int> c;
    int a, b;
    do {
        a = stk.top().first;
        b = stk.top().second;
        stk.pop();
        c.push_back(a);
        c.push_back(b);
    } while(a != x && b != y);

    sort(c.begin(), c.end());
    comp.push_back(c);
}

void dfs(int x, int t) {
    v[x] = 1;
    nivel[x] = low[x] = nivel[t]+1;
    for(auto next: g[x])
        if(!v[next]) {
            stk.push({x, next});
            dfs(next, x);
            if(low[next] >= nivel[x])
                add(x, next);
            low[x] = min(low[x], low[next]);
        } else if(next != t)
            low[x] = min(low[x], nivel[next]);
}

void solve() {
    for(int i = 1; i<= n; i++)
        if(!v[i])
            dfs(i, 0);
}

void afis() {
    fout << comp.size() << '\n';
    for(auto c: comp) {
        for(int i = 0; i < c.size(); i++)
            if(i == 0 || c[i] != c[i-1])
                fout << c[i] << ' ';
        fout << '\n';
    }
}

int main() {
    citire();
    solve();
    afis();
}