-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopologicalSort.cpp
More file actions
102 lines (85 loc) · 1.65 KB
/
TopologicalSort.cpp
File metadata and controls
102 lines (85 loc) · 1.65 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <iostream>
#include <vector>
#include <queue>
// QUESTION: https://www.techiedelight.com/topological-sorting-dag/
struct Edge
{
int src;
int dest;
};
struct Node
{
int number;
int departure_time;
bool operator()(const Node& left, const Node& right) const
{
return left.departure_time < right.departure_time;
}
};
class DirectedGraph
{
private:
std::vector<std::vector<int>> adj;
std::vector<bool> visited;
std::vector<Node> departure;
int nodes;
public:
DirectedGraph(int num, const std::vector<Edge> & edges)
: nodes(num)
{
adj.resize(nodes);
visited = std::vector<bool>(nodes, false);
departure = std::vector<Node>(nodes, { 0, -1 });
for (const auto& iter : edges)
{
adj[iter.src].push_back(iter.dest);
}
}
void topological()
{
int time = 0;
for (int i = 0; i < nodes; ++i)
{
if (!visited[i])
{
topologicalHelper(time, i);
}
}
// Create a max heap
std::priority_queue<Node, std::vector<Node>, Node> pq;
for (int i = 0; i < nodes; ++i)
{
pq.push(departure[i]);
}
std::cout << "The topological sort is " << std::endl;
while (!pq.empty())
{
Node top = pq.top();
pq.pop();
std::cout << top.number << " ";
}
std::cout << std::endl;
}
private:
void topologicalHelper(int& time, int start)
{
visited[start] = true;
++time;
for (const auto j : adj[start])
{
if (!visited[j])
{
topologicalHelper(time, j);
}
}
departure[start] = { start, ++time };
}
};
int main()
{
std::vector<Edge> edges{ {0, 6}, {1, 2}, {1, 4}, {1, 6}, {3, 0}, {3, 4}, {5, 1}, {7, 0}, {7, 1} };
int nodes = 8;
DirectedGraph obj(nodes, edges);
obj.topological();
return 0;
}