Cod sursa(job #2145770)

Utilizator andreicoman299Coman Andrei andreicoman299 Data 27 februarie 2018 16:44:51
Problema Componente biconexe Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>
#define MAXN 100010

std::vector <std::vector <int>> M;
std::vector <int> G[1 + MAXN], BC;
std::stack <std::pair<int, int>> S;
int depth[1 + MAXN], lowlink[1 + MAXN];
void writeComponent(int node){
    int ok = 1;
    BC.clear();
    while(ok){
        if(S.top().second == node) ok = 0;
        BC.push_back(S.top().first);
        S.pop();
    }
    BC.push_back(node);
    M.push_back(BC);
}
void tarjan(int node, int fth){
    depth[node] = lowlink[node] = depth[fth] + 1;
    for(auto y: G[node]){
        if(!depth[y]){
            S.push({y, node});
            tarjan(y, node);
            lowlink[node] = std::min(lowlink[node], lowlink[y]);
            if(lowlink[y] >= depth[node]) writeComponent(node);
        }
        if(y != fth) lowlink[node] = std::min(lowlink[node], depth[y]);
    }
}

int main(){
    FILE*fi,*fo;
    fi = fopen("biconex.in","r");
    fo = fopen("biconex.out","w");

    int n, m;
    fscanf(fi,"%d%d", &n, &m);
    for(int i = 1; i <= m; i++){
        int a, b;
        fscanf(fi,"%d%d", &a, &b);
        G[a].push_back(b);
        G[b].push_back(a);
    }
    tarjan(1, 0);
    fprintf(fo,"%d\n", M.size());
    for(int i = 0; i < M.size(); i++){
        for(auto j: M[i]) fprintf(fo,"%d ", j);
        fprintf(fo,"\n");
    }

    return 0;
}