Cod sursa(job #3039844)

Utilizator lolismekAlex Jerpelea lolismek Data 28 martie 2023 22:05:19
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <queue>

#include <iomanip>

using namespace std;

string filename = "biconex";

#ifdef LOCAL
    ifstream fin("input.in");
    ofstream fout("output.out");
#else
    ifstream fin(filename + ".in");
    ofstream fout(filename + ".out");
#endif

const int NMAX = 1e5;

vector <int> adj[NMAX + 1];

int nrComp = 0;
vector <int> comp[NMAX + 1];

int depth[NMAX + 1];
int lowLink[NMAX + 1];

stack <int> S;
bool viz[NMAX + 1];

void dfs(int node, int parent){
    depth[node] = lowLink[node] = depth[parent] + 1;    
    viz[node] = true;
    S.push(node);

    for(int vec : adj[node]){
        if(vec == parent){
            continue;
        }

        if(viz[vec]){
            lowLink[node] = min(lowLink[node], depth[vec]);
        }else{
            dfs(vec, node);
            lowLink[node] = min(lowLink[node], lowLink[vec]);

            if(lowLink[vec] >= depth[node]){
                ++nrComp;
                while(S.top() != vec){
                    comp[nrComp].push_back(S.top());
                    S.pop();
                }
                comp[nrComp].push_back(vec);
                S.pop();
                comp[nrComp].push_back(node);
            }
        }
    } 
}

signed main(){

    int n, m;
    fin >> n >> m;

    for(int i = 1; i <= m; i++){
        int a, b;
        fin >> a >> b;
        adj[a].push_back(b);
        adj[b].push_back(a);
    }

    dfs(1, 0);

    fout << nrComp << '\n';
    for(int i = 1; i <= nrComp; i++){
        for(int x : comp[i]){
            fout << x << ' ';
        }
        fout << '\n';
    }

    return 0;
}