-
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
/
Copy pathtopological_sort_by_kahns_algo.cpp
68 lines (62 loc) · 1.55 KB
/
topological_sort_by_kahns_algo.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#include <vector>
std::vector<int> topoSortKahn(int N, const std::vector<std::vector<int> > &adj);
int main() {
int nodes = 0, edges = 0;
std::cin >> edges >> nodes;
if (edges == 0 || nodes == 0) {
return 0;
}
int u = 0, v = 0;
std::vector<std::vector<int> > graph(nodes);
// create graph
// example
// 6 6
// 5 0 5 2 2 3 4 0 4 1 1 3
for (int i = 0; i < edges; i++) {
std::cin >> u >> v;
graph[u].push_back(v);
}
std::vector<int> topo = topoSortKahn(nodes, graph);
// topologically sorted nodes
for (int i = 0; i < nodes; i++) {
std::cout << topo[i] << " ";
}
}
std::vector<int> topoSortKahn(int V,
const std::vector<std::vector<int> > &adj) {
std::vector<bool> vis(V + 1, false);
std::vector<int> deg(V + 1, 0);
for (int i = 0; i < V; i++) {
for (int j : adj[i]) {
deg[j]++;
}
}
std::queue<int> q;
for (int i = 0; i < V; i++) {
if (deg[i] == 0) {
q.push(i);
vis[i] = true;
}
}
std::vector<int> arr(V + 1, 0);
int count = 0;
while (!q.empty()) {
int cur = q.front();
q.pop();
arr[count++] = cur;
for (int i : adj[cur]) {
if (!vis[i]) {
deg[i]--;
if (deg[i] == 0) {
q.push(i);
vis[i] = true;
}
}
}
}
return arr;
}