-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtopological_sort_bfs(khans).cpp
71 lines (64 loc) · 1.33 KB
/
topological_sort_bfs(khans).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
69
70
71
#include<bits/stdc++.h>
using namespace std;
int n,m;
vector<vector<int>>graph;
vector<int>indegree;;
vector<int>topo;
void khan(){
queue<int>q;
for(int i=1;i<=n;i++){
if(indegree[i]==0){
q.push(i);
}
}
while(!q.empty()){
int cur = q.front();
q.pop();
topo.push_back(cur);
for(auto v: graph[cur]){
indegree[v]--;
if(indegree[v]==0){
q.push(v);
}
}
}
}
//To print lexographically smallest topological sort
void khans(){
priority_queue<int>q;
for(int i=1;i<=n;i++){
if(indegree[i] == 0)
q.push(-i);
}
while(!q.empty()){
int cur = -q.top();
q.pop();
topo.push_back(cur);
for(auto v: graph[cur]){
indegree[v]--;
if(indegree[v] == 0){
q.push(-v);
}
}
}
}
int main(){
cin>>n>>m;
graph.resize(n+1);
indegree.resize(n+1,0);
for(int i=0;i<n;i++){
int u,v;
cin>>u>>v;
graph[u].push_back(v);
indegree[v]++;
}
khan();
if(topo.size() != n){ // if there is a cycle then all nodes are not inserted in topo
cout<<"There is a cycle"<<"\n";
}
else{
for(auto i: topo){
cout<<i<<" ";
}
}
}