// https://www.infoarena.ro/problema/ctc
// Complexitate: O(N + M) - algoritmul lui Kosaraju
// 1) DFS pe graf, retinem nodurile in ordinea terminarii
// 2) DFS pe graful transpus, in ordinea inversa a terminarii => fiecare DFS = o componenta
#include <bits/stdc++.h>
using namespace std;
const int NMAX = 100005;
FILE *fin = fopen("ctc.in", "r");
char buf[1 << 16];
int bpos = 0, blen = 0;
char urm() { // urmatorul caracter din fisier (citire rapida pe bucati)
if (bpos == blen) {
blen = fread(buf, 1, sizeof(buf), fin);
bpos = 0;
if (blen <= 0) return 0;
}
return buf[bpos++];
}
int citeste() {
char c = urm();
while (c && (c < '0' || c > '9')) c = urm();
int x = 0;
while (c >= '0' && c <= '9') {
x = x * 10 + (c - '0');
c = urm();
}
return x;
}
int n, m;
vector<int> g[NMAX], gt[NMAX]; // graful si graful transpus
bool viz1[NMAX], viz2[NMAX];
unsigned poz[NMAX]; // pana unde am parcurs lista de vecini a nodului
vector<int> ordine;
vector<vector<int>> componente;
// DFS iterativ pe graf: un nod intra in "ordine" cand i-am terminat toti vecinii
void dfs1(int rad) {
vector<int> st = {rad};
viz1[rad] = true;
while (!st.empty()) {
int nod = st.back();
if (poz[nod] < g[nod].size()) {
int v = g[nod][poz[nod]++];
if (!viz1[v]) {
viz1[v] = true;
st.push_back(v);
}
} else {
ordine.push_back(nod);
st.pop_back();
}
}
}
// pe graful transpus ne intereseaza doar ce noduri atingem => o parcurgere simpla cu stiva
void dfs2(int rad) {
componente.push_back({});
vector<int> st = {rad};
viz2[rad] = true;
while (!st.empty()) {
int nod = st.back();
st.pop_back();
componente.back().push_back(nod);
for (int v : gt[nod])
if (!viz2[v]) {
viz2[v] = true;
st.push_back(v);
}
}
}
int main() {
n = citeste();
m = citeste();
for (int i = 0; i < m; i++) {
int x = citeste(), y = citeste();
g[x].push_back(y);
gt[y].push_back(x);
}
for (int i = 1; i <= n; i++)
if (!viz1[i]) dfs1(i);
for (int i = n - 1; i >= 0; i--)
if (!viz2[ordine[i]]) dfs2(ordine[i]);
ofstream fout("ctc.out");
fout << componente.size() << "\n";
for (auto &c : componente) {
for (int x : c) fout << x << " ";
fout << "\n";
}
return 0;
}