Cod sursa(job #1641667)

Utilizator deneoAdrian Craciun deneo Data 9 martie 2016 09:33:39
Problema Componente biconexe Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.69 kb
#include <iostream>
#include <vector>
#include <stack>
#include <fstream>

using namespace std;

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

const int MAXN = 100100;

vector<int> graph[MAXN];

int n, m, used[MAXN], level[MAXN], in_stack[MAXN], how_high[MAXN];
stack<int> stiva;
vector<vector<int>> comp;

void baga_componenta(int last, int nod) {
    vector<int> compCurent;

    while (!stiva.empty() && stiva.top() != last) {
        compCurent.push_back(stiva.top());
        in_stack[stiva.top()] = 0;
        stiva.pop();
    }

    compCurent.push_back(last);
    stiva.pop();

    compCurent.push_back(nod);

    comp.push_back(compCurent);
}

void biconex (int nod, int lv) {
    level[nod] = lv;
    used[nod] = 1;
    in_stack[nod] = 1;
    stiva.push(nod);

    how_high[nod] = lv - 1;

    for (const auto& it : graph[nod]) {
        if (!used[it]) {
            biconex(it, lv + 1);
            how_high[nod] = min (how_high[nod], how_high[it]);
        }
        if (in_stack[it]) {
            how_high[nod] = min (how_high[nod], level[it]);
            if (how_high[it] == level[nod]) {
                baga_componenta(it, nod);
            }
        }
    }

}

int main() {

    fin >> n >> m;

    for (int i = 1; i <= m; ++i) {
        int x, y;
        fin >> x >> y;
        graph[x].push_back(y);
        graph[y].push_back(x);
    }

    for (int i = 1; i <= n; ++i) {
        if (!used[i])
            biconex(i, 1);
    }

    fout << comp.size() << "\n";

    for (int i = 0; i <comp.size(); ++i) {
        for (auto it: comp[i])
            fout << it << " ";
        fout << "\n";
    }


    return 0;
}