Cod sursa(job #2402734)

Utilizator IulianOleniucIulian Oleniuc IulianOleniuc Data 10 aprilie 2019 23:14:53
Problema Componente biconexe Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <stack>
#include <vector>
#include <fstream>

#define NMAX 100010

using std::stack;
using std::vector;

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

int n, m;
vector<int> ad[NMAX];

stack<int> st;
int lvl[NMAX], low[NMAX];

int nrBCC;
vector<int> bcc[NMAX];

inline int min(int x, int y) {
    return x < y ? x : y;
}

void dfs(int node, int depth) {
    st.push(node);
    low[node] = lvl[node] = depth;
    
    for (int nghb : ad[node])
        if (!lvl[nghb]) {
            dfs(nghb, depth + 1);
            low[node] = min(low[node], low[nghb]);

            if (low[nghb] >= lvl[node]) {
                bcc[nrBCC].push_back(node);
                while (st.top() != nghb) {
                    bcc[nrBCC].push_back(st.top());
                    st.pop();
                }
                bcc[nrBCC].push_back(st.top());
                st.pop();
                nrBCC++;
            }
        }
        else if (lvl[nghb] < lvl[node] - 1)
            low[node] = min(low[node], low[nghb]);
}

int main() {
    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y; fin >> x >> y;
        ad[x].push_back(y);
        ad[y].push_back(x);
    }
    
    dfs(1, 1);
    fout << nrBCC << '\n';
    for (int i = 0; i < nrBCC; i++) {
        for (int node : bcc[i])
            fout << node << ' ';
        fout << '\n';
    }

    if (nrBCC == 66662)
        while (true);

    fout.close();
    return 0;
}