-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopologicalSort.cpp
More file actions
75 lines (71 loc) · 1.64 KB
/
Copy pathTopologicalSort.cpp
File metadata and controls
75 lines (71 loc) · 1.64 KB
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
69
70
71
72
73
74
75
/**
* Author: Kevin Li
* Lang: C++
* Description: Topologically Sorts DAG
*/
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
#define MAXN 1000000
struct TopSort {
int n;
vector<int> *e;
int *degrees;
queue<int> topNodes;
vector<int> topologicalOrdering;
bool acyclic;
TopSort(int _n) : n(_n) {
e = new vector<int>[n];
degrees = new int[n];
acyclic = true;
for (int i = 0; i < n; i++) {
degrees[i] = 0;
}
}
void add(int u, int v) {
e[u].push_back(v);
degrees[v]++;
}
void checkAcyclic() {
if (topologicalOrdering.size() != n) {
acyclic = false;
}
}
void driver() {
for (int i = 0; i < n; i++) {
if (degrees[i] == 0) {
topNodes.push(i);
}
}
while (!topNodes.empty()) {
int topNode = topNodes.front();
topNodes.pop();
topologicalOrdering.push_back(topNode);
for (int i = 0; i < e[topNode].size(); i++) {
degrees[e[topNode][i]]--;
if (degrees[e[topNode][i]] == 0) {
topNodes.push(e[topNode][i]);
}
}
}
checkAcyclic();
}
void print() {
for (int i = 0; i < topologicalOrdering.size(); i++) {
cout << topologicalOrdering[i] << " ";
}
cout << endl;
}
};
int n,m;
int main() {
cin >> n >> m;
TopSort TS = TopSort(n);
for (int i = 0; i < m; i++) {
int u,v; cin >> u >> v;
TS.add(u,v);
}
TS.driver();
TS.print();
}