Cod sursa(job #1788057)

Utilizator andreiiiiPopa Andrei andreiiii Data 25 octombrie 2016 16:22:51
Problema Componente biconexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <algorithm>
#include <fstream>
#include <vector>
using namespace std;
 
const int NMAX = 100005;
vector<int> G[NMAX];
int level[NMAX], minlvl[NMAX];
 
int stk[NMAX];
int ctop = 0;
 
vector<vector<int>> components;
 
void addComponent(int node, int son) {
    vector<int> add;
    while (stk[ctop - 1] != son) {
        add.push_back(stk[ctop - 1]);
        ctop--;
    }
    add.push_back(stk[--ctop]);
    add.push_back(node);
    components.push_back(add);
}
 
void dfs(int node, int prev) {
    level[node] = level[prev] + 1;
    minlvl[node] = level[node];
    stk[ctop++] = node;
 
    for (int p: G[node]) {
        if (!level[p]) {
            dfs(p, node);
            minlvl[node] = min(minlvl[node], minlvl[p]);
            if (minlvl[p] >= level[node]) {
                addComponent(node, p);
            }
        } else {
            minlvl[node] = min(minlvl[node], level[p]);
        }
    }
}
 
int main() {
    ifstream fin("biconex.in");
    ofstream fout("biconex.out");
 
    int n, m;
    fin >> n >> m;
 
    for (int i = 0; i < m; ++i) {
        int x, y;
        fin >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
 
    dfs(1, 0);
 
    fout << components.size() << '\n';
    for (auto& component: components) {
        for (int node: component)
            fout << node << ' ';
        fout << '\n';
    }
 
    fin.close();
    fout.close();
}