Pagini recente » Cod sursa (job #2033617) | Istoria paginii runda/orange_morning/clasament | Cod sursa (job #1713029) | agm-2018/runda1 | Cod sursa (job #1304837)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#define nmax 100005
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
int n, m;
int timp = 0, nrComp = 0;
int final[nmax], ordin[nmax];
vector <int> G[nmax], GT[nmax];
stack <int> sol[nmax];
bool vizF[nmax], viz[nmax];
void readData() {
int i, x, y;
fin >> n >> m;
for (i = 1; i <= m; i++) {
fin >> x >> y;
G[x].push_back(y);
GT[y].push_back(x);
}
}
void DF_Final(int nod) {
int i;
vizF[nod] = true;
for (i = 0; i < G[nod].size(); i++)
if (!vizF[G[nod][i]])
DF_Final(G[nod][i]);
timp++;
final[nod] = timp;
}
void DF(int nod) {
int i;
viz[nod] = true;
for (i = 0; i < GT[nod].size(); i++)
if (!viz[GT[nod][i]]) {
sol[nrComp].push(GT[nod][i]);
DF(GT[nod][i]);
}
}
void solve() {
int i, k;
for (i = 1; i <= n; i++)
if (!vizF[i])
DF_Final(i);
for (i = 1; i <= n; i++)
ordin[n - final[i] + 1] = i;
for (i = 1; i <= n; i++) {
k = ordin[i];
if (!viz[k]) {
nrComp++;
sol[nrComp].push(k);
DF(k);
}
}
fout << nrComp << "\n";
for (i = 1; i <= nrComp; i++) {
while (!sol[i].empty()) {
fout << sol[i].top() << " ";
sol[i].pop();
}
fout << "\n";
}
}
int main() {
readData();
solve();
fin.close();
fout.close();
return 0;
}