-
Notifications
You must be signed in to change notification settings - Fork 33
/
Topological_Sort.cpp
46 lines (44 loc) · 991 Bytes
/
Topological_Sort.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
#include <bits/stdc++.h>
using namespace std;
vector<int > adj[100];
void topo_sort(int n){
queue<int > q;
vector<int> vis(n+2,0);
vector<int> indegree(n+2,0);
for(int i=1;i<=n;i++){
for(int j=0;j<adj[i].size();j++)
{
indegree[adj[i][j]]++;
//cout<<adj[i][j]<<" ";
}
//cout<<endl;
}
for(int i=1;i<=n;i++){
//cout<<i<<" "<<indegree[i]<<endl;
if(indegree[i]==0){//push vertex with 0 indegree
q.push(i);
}
}
while(!q.empty()){
int x=q.front();
q.pop();
cout<<x<<" ";
for(int i=0;i<adj[x].size();i++){
indegree[adj[x][i]]--;
if(indegree[adj[x][i]]==0){
q.push(adj[x][i]);
}
}
}
}
int main() {
int n,e;
cin>>n>>e;
for(int i=0;i<e;i++){
int x,y;
cin>>x>>y;
adj[x].push_back(y);
//adj[y].push_back(x);
}
topo_sort(n);
}