Cod sursa(job #2574160)

Utilizator IulianOleniucIulian Oleniuc IulianOleniuc Data 5 martie 2020 20:39:45
Problema Componente biconexe Scor 42
Compilator cpp-64 Status done
Runda OJI 2020 Partea a II-a Marime 1.18 kb
#include <bits/stdc++.h>
using namespace std;

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

int n, m;
vector<vector<int>> ad;

stack<int> st;
vector<int> lvl, low;
vector<vector<int>> bccs;

void dfs(int node, int father) {
    st.push(node);
    lvl[node] = low[node] = lvl[father] + 1;
    for (int nghb : ad[node])
        if (!lvl[nghb]) {
            dfs(nghb, node);
            low[node] = min(low[node], low[nghb]);
            if (low[nghb] >= lvl[node]) {
                bccs.emplace_back(1, node);
                while (st.top() != node) {
                    bccs.back().push_back(st.top());
                    st.pop();
                }
            }
        }
        else if (nghb != father)
            low[node] = min(low[node], low[nghb]);
}

int main() {
    fin >> n >> m;
    ad.resize(n + 1);
    for (int i = 0; i < m; i++) {
        int x, y; fin >> x >> y;
        ad[x].push_back(y);
        ad[y].push_back(x);
    }

    lvl.resize(n + 1);
    low.resize(n + 1);
    dfs(1, 0);

    fout << bccs.size() << '\n';
    for (auto& bcc : bccs) {
        for (int node : bcc)
            fout << node << ' ';
        fout << '\n';
    }

    fout.close();
    return 0;
}