Cod sursa(job #3030826)

Utilizator redstonegamer22Andrei Ion redstonegamer22 Data 17 martie 2023 21:50:23
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>

using namespace std;

#ifndef LOCAL
ifstream in("biconex.in");
ofstream out("biconex.out");
#define cin in
#define cout out
#endif // LOCAL

const int NMAX = 1e5 + 7;
int depth[NMAX], low[NMAX];
vector<vector<int>> cc;

vector<int> g[NMAX];
stack<int> stk;

void dfs(int node, int father, int d) {
    depth[node] = d;
    low[node] = d;

    stk.push(node);

    for(auto vec : g[node]) {
        if(vec == father) continue;

        if(depth[vec] != 0) { low[node] = min(low[node], depth[vec]); continue; }

        dfs(vec, node, d + 1);
        if(low[vec] >= depth[node]) {
            vector<int> c;
            while(!stk.empty() && stk.top() != vec) {
                c.push_back(stk.top());
                stk.pop();
            }

            stk.pop(); c.push_back(node); c.push_back(vec);
            cc.push_back(c);
        }

        low[node] = min(low[node], low[vec]);
    }
}

int main() {
    int n, m; cin >> n >> m;
    for(int i = 0; i < m; i++) {
        int x, y; cin >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }

    for(int i = 1; i <= n; i++) {
        if(depth[i] == 0) dfs(i, i, 1);
    }

    cout << cc.size() << '\n';
    for(auto e : cc) {
        for(auto ee : e) cout << ee << " ";
        cout << '\n';
    }
}