Cod sursa(job #2581985)

Utilizator vlad082002Ciocoiu Vlad vlad082002 Data 16 martie 2020 11:00:19
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <fstream>
#include <vector>
#include <cstring>
#include <stack>
#include <iostream>
#include <algorithm>
using namespace std;

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

vector<int> g[100005];
vector<vector<int> > bi;
bool v[100005];
int n, m;
stack<pair<int, int> > st;
int low[100005], nivel[100005];

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) {
    pair<int, int> p;
    vector<int> c;
    do {
        p = st.top();
        st.pop();
        c.push_back(p.first);
        c.push_back(p.second);
    } while(p.first != x || p.second != y);
    sort(c.begin(), c.end());
    bi.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]) {
            st.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 << bi.size() << '\n';
    for(auto x: bi) {
        for(int i = 0; i < x.size(); i++)
            if(i == 0 || x[i] != x[i-1])
                fout << x[i] << ' ';
        fout << '\n';
    }
}

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