-
Notifications
You must be signed in to change notification settings - Fork 1
/
topological_sort.cpp
94 lines (89 loc) · 1.03 KB
/
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
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
84
85
86
87
88
89
90
91
92
93
94
#include<bits/stdc++.h>
using namespace std;
int v,E;
vector <vector <int> > g;
int stacky[10000];
int vis[1000];
int sp=0;
int ans1[100000];
int po=0;
int cur;
int push(int val)
{
stacky[sp]=val;
sp++;
}
int pop()
{
sp--;
}
int dfs()
{
int p =cur;
//cout << p << endl;
for(int j=0 ; j< g[cur].size() ; j++)
{
int k = g[cur][j];
//cout << k << endl;
if(vis[k]==0)
{
push(cur);
cur=k;
vis[k]=1;
dfs();
}
if(cur==p)
{
if(sp==0)
{
//cout << cur << " ";
return 0;
}
else
{
//cout << cur << " ";
ans1[po]=cur;
po++;
vis[cur]=2;
int t = stacky[sp-1];
pop();
cur=t;
dfs();
}
}
}
int main ()
{
cin >> v >> E;
g.resize(v+1);
for(int i=0 ; i<E;i++)
{
int v1,v2;
cin >> v1 >> v2;
if(i==0)
{
cur=v1;
}
g[v1].push_back(v2);
}
for(int i=1;i<=v ; i++)
{
vis[i]=0;
}
for(int i=1;i<=v;i++)
{
if(vis[i] == 0)
{
cur=i;
vis[i]=1;
dfs();
ans1[po]=i;
po++;
vis[cur]=2;
}
}
for(int i= po-1;i>=0 ;i--)
{
cout << ans1[i] << " ";
}
}