Pagini recente » Cod sursa (job #1731118) | Cod sursa (job #1579879) | Cod sursa (job #1594979) | Cod sursa (job #2149344) | Cod sursa (job #1254258)
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
const int kMaxN = 100005;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
int N, M, ctc_n;
vector<int> G[kMaxN], T[kMaxN], ctc[kMaxN];
stack<int> st;
bool use[kMaxN];
void NormalDFS(int node) {
use[node] = true;
for (int i : G[node])
if (!use[i])
NormalDFS(i);
st.push(node);
}
void TransposeDFS(int node) {
use[node] = false;
ctc[ctc_n].push_back(node);
for (int i : T[node])
if (use[i])
TransposeDFS(i);
}
void Read() {
fin >> N >> M;
while (M--) {
int x, y;
fin >> x >> y;
G[x].push_back(y);
T[y].push_back(x);
}
}
void Kosaraju() {
for (int i = 1; i <= N; ++i)
if (!use[i])
NormalDFS(i);
while (!st.empty()) {
if (use[st.top()]) {
++ctc_n;
TransposeDFS(st.top());
}
st.pop();
}
}
void Print() {
fout << ctc_n << "\n";
for (int i = 1; i <= ctc_n; ++i) {
for (int node : ctc[i])
fout << node << " ";
fout << "\n";
}
}
int main() {
Read();
Kosaraju();
Print();
return 0;
}