Cod sursa(job #2153700)

Utilizator CammieCamelia Lazar Cammie Data 6 martie 2018 13:47:33
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <fstream>
#include <vector>
#include <memory.h>

#define MAXN 100005

using namespace std;

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

int N, M, sol, viz[MAXN], postordine[MAXN], nn;

vector <int> s[MAXN], graph[MAXN], tr[MAXN];

inline void Read() {
    int x, y;

    fin >> N >> M;

    for (int i = 1; i <= M; i++) {
        fin >> x >> y;

        graph[x].push_back(y);
        tr[y].push_back(x);
    }
}

inline void DFS(int node) {
    viz[node] = 1;

    for (auto x : graph[node]) {
        if (!viz[x])
            DFS(x);
    }

    postordine[++nn] = node;
}

inline void DFST(int node) {
    viz[node] = 1; s[sol].push_back(node);

    for (auto x : tr[node]){
        if (!viz[x])
            DFST(x);
    }
}

int main () {
    Read();

    for (int i = 1; i <= N; i++) {
        if (!viz[i])
            DFS(i);
    }

    memset(viz, 0, sizeof(viz));

    for (int i = nn; i; i--) {
        if (!viz[postordine[i]]) {
            sol++;
            DFST(postordine[i]);
        }
    }

    fout << sol << "\n";

    for (int i = 1; i <= sol; i++) {
        for (auto x : s[i])
            fout << x << " ";
        fout << "\n";
    }

    fin.close(); fout.close(); return 0;
}