Cod sursa(job #2846944)

Utilizator Tudor06MusatTudor Tudor06 Data 9 februarie 2022 21:16:41
Problema Componente biconexe Scor 46
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 1e5;

vector <int> edges[NMAX + 1];
int viz[NMAX + 1];
int depth[NMAX + 1];
int mindepth[NMAX + 1];

stack <int> s;

vector <int> biconexe[NMAX];
int nrbic;

void dfs( int node, int father ) {
    viz[node] = 1;
    depth[node] = mindepth[node] = depth[father] + 1;
    s.push( node );
    for ( auto it : edges[node] ) {
        if ( it == father ) continue;

        if ( viz[it] ) {
            mindepth[node] = min( mindepth[node], depth[it] );
        } else {
            dfs( it, node );
            mindepth[node] = min( mindepth[node], mindepth[it] );
            if ( mindepth[it] >= depth[node] ) {
                while ( s.top() != node ) {
                    biconexe[nrbic].push_back( s.top() );
                    s.pop();
                }
                biconexe[nrbic].push_back( node );
                nrbic ++;
            }
        }
    }
}

int main() {
    ifstream fin( "biconex.in" );
    ofstream fout( "biconex.out" );
    int n, m, i, a, b;
    fin >> n >> m;
    for ( i = 0; i < m; i ++ ) {
        fin >> a >> b;
        edges[a].push_back( b );
        edges[b].push_back( a );
    }
    for ( i = 1; i <= n; i ++ ) {
        if ( !viz[i] ) {
            dfs( i, 0 );
        }
    }

    fout << nrbic << '\n';
    for ( i = 0; i < nrbic; i ++ ) {
        for ( auto it : biconexe[i] )
            fout << it << ' ';
        fout << '\n';
    }
    return 0;
}