Cod sursa(job #1969933)

Utilizator mariapascuMaria Pascu mariapascu Data 18 aprilie 2017 18:54:03
Problema Componente biconexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.73 kb
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

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

using VI = vector<int>;
using VVI = vector<VI>;
using VB = vector<bool>;
using SPII = stack<pair<int,int>>;

int n, m;
VVI G, CC;
VI niv, L, t, C;
VB s;
SPII Stk;

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

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

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

void Write() {
    fout << CC.size() << '\n';
    for (auto & c : CC) {
        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 = VVI(n + 1);
    niv = L = t = VI(n + 1);
    s = VB(n + 1);
    int x, y;
    for (int i = 1; i <= m; i++) {
        fin >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
}