Cod sursa(job #1650711)

Utilizator mariapascuMaria Pascu mariapascu Data 11 martie 2016 20:02:20
Problema Componente biconexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.76 kb
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

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

int n, m;
vector<vector<int>> G;
vector<int> t, niv, L;
vector<bool> s;
int root;

vector<vector<int>> C;
vector<int> c;
stack<pair<int, int> > S;
int x1, x2;

void Read();
void DFS(int x, int nv);
void Write();

int main() {
    Read();
    root = 1;
    DFS(root, 1);
    Write();
    fin.close();
    fout.close();
    return 0;
}

void DFS(int x, int nv) {
    L[x] = niv[x] = nv;
    s[x] = true;
    for (const auto & y : G[x]) {
        if (y == t[x]) continue;
        if (!s[y]) {
            t[y] = x;
            S.push({x, y});
            DFS(y, nv + 1);
            L[x] = min(L[x], L[y]);
            if (niv[x] <= L[y]) {
                c.clear();
                while (true) {
                    x1 = S.top().first;
                    x2 = S.top().second;
                    S.pop();
                    c.push_back(x1);
                    c.push_back(x2);
                    if (x1 == x && x2 == y) break;
                }
                C.push_back(c);
            }
        }
        else L[x] = min(L[x], niv[y]);
    }
}

void Write() {
    fout << C.size() << '\n';
    for (auto & c : C) {
        sort(c.begin(), c.end());
        c.erase(unique(c.begin(), c.end()), c.end());
        for (const auto & x : c)
            fout << x << ' ';
        fout <<'\n';
    }
}

void Read() {
    fin >> n >> m;
    G = vector<vector<int>>(n + 1);
    t = niv = L = vector<int>(n + 1);
    s = vector<bool>(n + 1);
    for (int i = 1, x, y; i <= m; i++) {
        fin >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
}