forked from codersinghal/Competitive-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoposort.cpp
More file actions
83 lines (71 loc) · 1.4 KB
/
toposort.cpp
File metadata and controls
83 lines (71 loc) · 1.4 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
/**
* Description: Topological sorting
* Usage: See below O(V + E)
* Source: https://github.com/dragonslayerx
*/
#include <bits/stdc++.h>
using namespace std;
#define SIZE 100000
vector<int> graph[SIZE];
int visited[SIZE] = {0};
stack<int> topoOrder;
void toposort(int node) {
visited[node] = 1;
for(int adj: graph[node]) {
if(!visited[adj]) {
toposort(adj);
}
}
topoOrder.push(node);
}
int main() {
int n, m;
int indegree[SIZE] = {0};
// here n is no of nodes and m is no of edges
cin>>n>>m;
// taking directed edges as input
for(int i=0;i<m;i++) {
int u, v;
cin>>u>>v;
graph[u].push_back(v);
indegree[v]++;
}
// toposort using dfs
printf("Using dfs, Topological Sort: \n");
for(int i=1;i<=n;i++) {
// we need to call dfs for all disconnected components if present
if(!visited[i]) {
toposort(i);
}
}
while(!topoOrder.empty()) {
printf("%d ", topoOrder.top());
topoOrder.pop();
}
printf("\n");
// toposort using indegree approach
printf("Using in-degree method, Topological Sort: \n");
queue<int> q;
vector<int> topoOrder2;
for(int i=1;i<=n;i++) {
if(indegree[i] == 0) {
q.push(i);
}
}
while(!q.empty()) {
int curr = q.front();
topoOrder2.push_back(curr);
q.pop();
for(int adj: graph[curr]) {
indegree[adj]--;
if(indegree[adj] == 0) {
q.push(adj);
}
}
}
for(int node: topoOrder2) {
printf("%d ", node);
}
printf("\n");
return 0;
}