Pagini recente » Cod sursa (job #1012078) | Cod sursa (job #2213659) | Cod sursa (job #746420) | Cod sursa (job #253383) | Cod sursa (job #2123156)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
vector <int> v[100001], vt[100001], sol[100001];
int s, n, m, color[100001], c;
stack <int> stash;
void citire () {
fin >> n >> m;
for (int i = 1; i <= m; ++i) {
int x, y;
fin >> x >> y;
v[x].push_back(y);
vt[y].push_back(x);
}
}
/// if there is any edge other than "tree", then the graph has at least a cycle
void dfs (int nod) {
color[nod] = 1;
int size = v[nod].size();
for (int i = 0; i < size; ++i) {
int y = v[nod][i];
if (color[y] == 0) {
//fout << nod << " " << y << " " << "tree" << '\n';
dfs(y);
}
}
color[nod] = 2;
stash.push(nod);
}
void color_index () {
for (int i = 1; i <= n; ++i) {
color[i] = 0;
}
}
void dfst (int nod) {
sol[c].push_back(nod);
color[nod] = 1;
int size = vt[nod].size();
for (int i = 0; i < size; ++i) {
int y = vt[nod][i];
if (color[y] == 0) {
//fout << nod << " " << y << " " << "tree" << '\n';
dfst(y);
}
}
color[nod] = 2;
}
int main () {
citire();
for (int i = 1; i <= n; ++i) {
if (color[i] == 0) {
dfs(i);
}
}
color_index();
while (not stash.empty()) {
if (color[stash.top()] == 0) {
c++;
dfst(stash.top());
}
stash.pop();
}
fout << c;
fout << '\n';
for (int i = 1; i <= c; ++i) {
int size = sol[i].size();
for (int j = 0; j < size; ++j) {
fout << sol[i][j] << " ";
}
fout << '\n';
}
}