Pagini recente » Cod sursa (job #2724680) | Cod sursa (job #1030875) | Cod sursa (job #2403867) | Cod sursa (job #1257111) | Cod sursa (job #1304250)
#define IA_PROB "ctc"
#include <cassert>
#include <cstdio>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;
typedef int node;
typedef stack<node, vector<node> > node_stack;
typedef list<node> adj_list;
typedef vector<adj_list> graph;
void dfs(graph &G, vector<bool> &seen, node_stack &stack, node x)
{
assert(!seen[x]);
seen[x] = true;
for (adj_list::iterator i = G[x].begin(); i != G[x].end(); i++) {
if (!seen[*i]) {
dfs(G, seen, stack, *i);
}
}
stack.push(x);
}
int main()
{
freopen(IA_PROB".in", "r", stdin);
freopen(IA_PROB".out", "w", stdout);
int n, m;
scanf("%d %d", &n, &m);
graph G(n + 1);
for (int i = 0; i < m; i++) {
int x, y;
scanf("%d %d", &x, &y);
G[x].push_back(y);
}
node_stack topo_stack;
vector<bool> seen(n + 1);
for (int i = 1; i <= n; i++) {
if (!seen[i]) {
dfs(G, seen, topo_stack, i);
}
}
/* reverse graph */
graph Gr(n + 1);
for (node i = 1; i <= n; i++) {
for (adj_list::iterator j = G[i].begin(); j != G[i].end(); j++) {
Gr[*j].push_back(i);
}
}
/* release old G */
G.clear();
/* reset seen */
fill(seen.begin(), seen.end(), false);
/* dfs on the reversed graph, starting from nodes in topological order */
vector<node_stack> sccs;
while (!topo_stack.empty()) {
node node = topo_stack.top();
topo_stack.pop();
if (!seen[node]) {
sccs.push_back(node_stack());
dfs(Gr, seen, sccs.back(), node);
}
}
/* print result */
printf("%d\n", sccs.size());
for (vector<node_stack>::iterator i = sccs.begin(); i != sccs.end(); i++) {
while (!i->empty()) {
printf("%d ", i->top());
i->pop();
}
printf("\n");
}
return 0;
}