Cod sursa(job #3373443)

Utilizator teodorescunicolasteodorescu nicolas alexandru teodorescunicolas Data 7 noiembrie 2026 01:44:23
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.22 kb
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>

#define NMAXX 100000

using namespace std;

ifstream cin("biconex.in");
ofstream cout("biconex.out");

vector<pair<int, int>> graph[NMAXX + 1];
vector<vector<int>> componente;
stack<pair<int, int>> st;

int disc[NMAXX + 1], low[NMAXX + 1];
int viz[NMAXX + 1];

void dfs( int node, int parent, int &timer ) {
    int nr;

    disc[node] = timer;
    low[node] = timer;
    timer++;
    for ( auto vecin : graph[node] ) {
        int poz = vecin.first;
        int id = vecin.second;

        if ( id != parent ) {
            if ( disc[poz] == 0 ) {
                st.push({node, poz} );

                dfs(poz, id, timer );

                low[node] = min(low[node], low[poz] );

                if ( low[poz] >= disc[node] ) {
                    vector<int> comp;
                    nr = componente.size() + 1;

                    while (true) {
                        int x = st.top().first;
                        int y = st.top().second;
                        st.pop();

                        if (viz[x] != nr) {
                            viz[x] = nr;
                            comp.push_back(x);
                        }

                        if ( viz[y] != nr ) {
                            viz[y] = nr;
                            comp.push_back(y);
                        }

                        if ( x == node && y == poz )
                            break;
                    }
                    componente.push_back( comp );
                }
            }
            else if ( disc[poz] < disc[node] ) {
                st.push({node, poz});
                low[node] = min(low[node], disc[poz]);
            }
        }
    }
}

int main() {
    int n, m, x, y, i, timer;

    cin >> n >> m;
    for ( i = 1; i <= m; i++ ) {
        cin >> x >> y;
        graph[x].push_back({y, i});
        graph[y].push_back({x, i});
    }

    timer = 0;
    for ( i = 1; i <= n; i++ ) {
        if ( disc[i] == 0 ) {
            dfs(i, -1, timer );
        }
    }

    cout << componente.size() << '\n';
    for ( auto comp : componente ) {
        for ( auto poz : comp ) {
            cout << poz << ' ';
        }

        cout << '\n';
    }

    return 0;
}