Cod sursa(job #3030949)

Utilizator redstonegamer22Andrei Ion redstonegamer22 Data 18 martie 2023 00:23:45
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 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;
vector<int> g[NMAX];
vector<vector<int>> cc;

int depth[NMAX], low[NMAX];

stack<int> stk;

void dfs(int node, int fat, int d) {
    depth[node] = low[node] = d;
    stk.push(node);

    for(auto vec : g[node]) {
        if(vec == fat) 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(vec); c.push_back(node);
            cc.push_back(c);
        }

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

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 c : cc) {
        for(auto e : c) cout << e << " ";
        cout << '\n';
    }

    return 0;
}