Cod sursa(job #2723037)

Utilizator marius004scarlat marius marius004 Data 13 martie 2021 14:58:37
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <stack>

using namespace std;

ifstream f("ctc.in");
ofstream g("ctc.out");

const int NMAX = 100010;

int n, m, cnt;
vector < int  > G[NMAX], GT[NMAX];
vector < int > scc[NMAX];
bitset < NMAX > beenThere;
stack < int > ord;

void dfs(int node) {

    beenThere[node] = 1;

    for(auto& it : G[node])
        if(!beenThere[it])
            dfs(it);

    ord.push(node);
}

void dfs2(int node) {

    scc[cnt].push_back(node);
    beenThere[node] = 1;

    for(auto& it : GT[node])
        if(!beenThere[it])
            dfs2(it);
}

void kosoraju() {

    for(int i = 1;i <= n;++i)
        if(!beenThere[i])
            dfs(i);

    beenThere.reset();

    for(;!ord.empty();ord.pop()) {
        if(!beenThere[ord.top()]) {
            cnt++;
            dfs2(ord.top());
        }
    }
}

int main() {

    f >> n >> m;

    for(;m--;) {
        int x, y;
        f >> x >> y;

        G[x].push_back(y);
        GT[y].push_back(x);
    }

    kosoraju();

    g << cnt << '\n';

    for(int i = 1;i <= cnt;++i) {

        for(auto& it : scc[i])
            g << it << ' ';

        g << '\n';
    }

    return 0;
}