-
Notifications
You must be signed in to change notification settings - Fork 208
/
Copy pathTopoLogicalSort
57 lines (57 loc) · 968 Bytes
/
TopoLogicalSort
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
#include <bits/stdc++.h>
using namespace std;
class Edge
{
public:
int source;
int neighbour;
int weight;
void add(int source, int neighbour, int weight)
{
this->source = source;
this->neighbour = neighbour;
this->weight = weight;
}
};
void topologicalSort(std::vector<Edge> v[], int source, bool *vis, stack<int>&st)
{
vis[source] = true;
for (auto E : v[source])
{
if (vis[E.neighbour] == false)
{
topologicalSort(v, E.neighbour, vis, st);
}
}
st.push(source);
}
int main()
{
int vertices;
cin >> vertices;
vector<Edge> adj[vertices];
int edge; cin >> edge;
for (int i = 0; i < edge; i++)
{
int v1, v2, weight = 1;
cin >> v1 >> v2;
Edge p1;
p1.add(v1, v2, weight);
adj[v1].push_back(p1);
}
bool vis[vertices] = {false};
stack<int>st;
for (int i = 0; i < vertices; i++)
{
if (vis[i] == false)
{
topologicalSort(adj, i, vis, st);
}
}
while (st.size())
{
cout << st.top() << " ";
st.pop();
}
return 0;
}