Skip to content

Commit 3d26eaa

Browse files
authored
Merge pull request AllAlgorithms#205 from raunak96/master
Added Topological Sort
2 parents c9b55ff + c9a4ab8 commit 3d26eaa

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

graphs/toposort.cpp

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
vector<int> adj[10001];
4+
priority_queue<int,vector<int>,greater<int> >q;
5+
queue<int>a;
6+
bool visited[10001];
7+
int indegree[10001];
8+
int main()
9+
{
10+
int n,m,u,v;
11+
scanf("%d%d",&n,&m);
12+
while(m--)
13+
{
14+
scanf("%d%d",&u,&v);
15+
adj[u].push_back(v);
16+
indegree[v]++;
17+
}
18+
for(int i=1;i<=n;i++)
19+
if(!indegree[i])
20+
q.push(i);
21+
int k=0;
22+
while(!q.empty())
23+
{
24+
int u=q.top();
25+
q.pop();
26+
a.push(u);
27+
for(auto it:adj[u])
28+
{
29+
indegree[it]--;
30+
if(!indegree[it])
31+
q.push(it);
32+
}
33+
++k;
34+
}
35+
if(k!=n)
36+
printf("Sandro fails.");
37+
else
38+
{
39+
while(!a.empty())
40+
{
41+
printf("%d ",a.front());
42+
a.pop();
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)