In computer science, a topological sort or topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge uv from vertex u to vertex v, u comes before v in the ordering.
int cnt[MAXN]; // cnt[v] means the number of edges end with v vector<int> from[MAXN]; // to[v] stores ends of edges starting from int result[MAXN], idx; bool vis[MAXN]; // wether a vertx is already in the result list
intmain() { int n, m; // n for vertices, m for edges
scanf("%d%d", &n, &m); for (int i = 0; i != m; ++i) { int u, v; // an edge from u to v scanf("%d%d", &u, &v); from[u].push_back(v); ++cnt[v]; }
while (idx != n) { bool flag = true; for (int i = 1; i <= n; ++i) { if (!vis[i] && !cnt[i]) { flag = false; vis[i] = true; result[idx++] = i; for (int j : from[i]) --cnt[j]; } } if (flag) // finding no vertex with no predecessor puts("Not a DAG (cyclic graph)."), exit(0); }
// print vertices out in topological order printf("%d", result[0]); for (int i = 1; i != n; ++i) printf(" %d", result[i]); puts(""); }
vector<int> from[MAXN]; // to[v] stores ends of edges starting from v int result[MAXN], idx; bool perm[MAXN], temp[MAXN]; // permanent mark and temporary mark
voiddfs(int u) { if (temp[u]) puts("Not a DAG (cyclic graph)."), exit(0); temp[u] = true; for (int v : from[u]) if (!perm[v]) dfs(v); temp[u] = false; perm[u] = true; // mind that recursion means deferred operations // that's why we have to do insertions from back to front result[--idx] = u; }
intmain() { int n, m; // n for vertices, m for edges
scanf("%d%d", &n, &m); idx = n; for (int i = 0; i != m; ++i) { int u, v; // an edge from u to v scanf("%d%d", &u, &v); from[u].push_back(v); }
while (idx) for (int i = 1; i <= n; ++i) if (!perm[i]) dfs(i);
// print vertices out in topological order printf("%d", result[0]); for (int i = 1; i != n; ++i) printf(" %d", result[i]); puts(""); }
voiddfs(int u) { if (dp[u]) return; for (int v : from[u]) { dfs(v); dp[u] = max(dp[u], 1 + dp[v]); } if (dp[u] > ans) ans = dp[u]; }
intmain() { int n, m; scanf("%d%d", &n, &m); for (int i = 0; i != m; ++i) { int u, v; scanf("%d%d", &u, &v); from[u].push_back(v); } for (int i = 1; i <= n; ++i) if (!dp[i]) dfs(i); printf("%d\n", ans); }