Cod sursa(job #2637270)

Utilizator vlad082002Ciocoiu Vlad vlad082002 Data 22 iulie 2020 10:59:34
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;

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

int n, m, low[100005], nivel[100005], v[100005];
vector<int> g[100005];
vector<vector<int> > comp;
stack<pair<int, int> > stk;

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) {
    int a, b;
    vector<int> c;
    do {
        a = stk.top().first;
        b = stk.top().second;
        c.push_back(a);
        c.push_back(b);
        stk.pop();
    } while(a != x && b != y && !stk.empty());
    sort(c.begin(), c.end());
    comp.push_back(c);
}

void dfs(int x, int t) {
    v[x] = 1;
    low[x] = nivel[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 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();
    dfs(1, 0);
    afis();
}