Cod sursa(job #2722558)

Utilizator IoanaDraganescuIoana Draganescu IoanaDraganescu Data 12 martie 2021 23:24:49
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <algorithm>

using namespace std;

ifstream fin("ctc.in");
ofstream fout("ctc.out");

const int NMax = 1e5;

vector <int> g[NMax + 5], tg[NMax + 5], topsort, answer[NMax + 5];
int n, m, code;
bool use[NMax + 5];

void Read(){
    fin >> n >> m;
    while (m--){
        int x, y;
        fin >> x >> y;
        g[x].push_back(y);
        tg[y].push_back(x);
    }
}

void TopologicalSort(int node){
    use[node] = 1;
    for (auto ngh : g[node])
        if (!use[ngh])
            TopologicalSort(ngh);
    topsort.push_back(node);
}

void DFS(int node, int code){
    use[node] = 1;
    answer[code].push_back(node);
    for (auto ngh : tg[node])
        if (!use[ngh])
            DFS(ngh, code);
}

void Solve(){
    for (int i = 1; i <= n; i++)
        if (!use[i])
            TopologicalSort(i);
    reverse(topsort.begin(), topsort.end());
    memset(use, 0, sizeof use);
    for (auto node : topsort)
        if (!use[node]){
            DFS(node, code);
            code++;
        }
}

void Print(){
    fout << code << '\n';
    for (int i = 0; i < code; i++){
        for (auto node : answer[i])
            fout << node << ' ';
        fout << '\n';
    }
}

int main(){
    Read();
    Solve();
    Print();
    return 0;
}