-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathKahnsALgorithm.cpp
More file actions
56 lines (56 loc) · 1.17 KB
/
KahnsALgorithm.cpp
File metadata and controls
56 lines (56 loc) · 1.17 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
#include<bits/stdc++.h>
using namespace std;
vector<int> Topological_sort(vector<int> adj[],int indegree[], int vertices)
{
vector <int> ans;
int count = 0;
queue <int> q;
for(int i=0;i<vertices;i++){
if(indegree[i]==0){
q.push(i);
}
}
while(!q.empty()){
int curr = q.front();
count++;
ans.push_back(curr);
q.pop();
for(auto s: adj[curr]){
indegree[s]--;
if(indegree[s]==0){
q.push(s);
}
}
}
vector<int> a;
if(count!=vertices){
return a;
}
else{
return ans;
}
}
int main(){
int vertices, edges; cin>>vertices>>edges;
vector <int> adj[vertices];
int a,b;
for(int i=0;i<edges;i++){
cin>>a>>b;
adj[a].push_back(b);
}
int degree[vertices];
for(int i=0;i<vertices;i++){
degree[i] = false;
}
for(int i=0;i<vertices;i++){
for(auto s: adj[i]){
degree[s]++;
}
}
vector<int> ans;
ans = Topological_sort(adj, degree, vertices);
for(auto s:ans){
cout<<s<<" ";
}cout<<endl;
return 0;
}