Cod sursa(job #2325067)

Utilizator andra_moldovanAndra Moldovan andra_moldovan Data 21 ianuarie 2019 22:00:29
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <fstream>
#include <vector>
#include <cstring>

#define MAXN 100005

using namespace std;

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

int N, M, viz[MAXN];
int postorder[MAXN], nn;

vector <int> s[MAXN]; int sol;
vector <int> 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);
    }
    postorder[++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);
    }
}

inline void Solve() {
    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[postorder[i]]) {
            sol++;
            DFST(postorder[i]);
        }
    }
}

inline void Write() {
    fout << sol << "\n";

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

int main () {
    Read();
    Solve();
    Write();

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