-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathTopological_Sort.cpp
More file actions
73 lines (60 loc) · 1.19 KB
/
Topological_Sort.cpp
File metadata and controls
73 lines (60 loc) · 1.19 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <bits/stdc++.h>
using namespace std ;
#define lli long long int
#define pb push_back
#define MAXN 10000
int n , m , a , b ;
vector <int> adj [MAXN] ;
int grau [MAXN];
vector <int> order ;
bool topological_sort ()
{
int ini = 0 ;
while (ini < order.size())
{
int atual = order[ini] ;
ini++ ;
for (int i = 0 ; i < adj[atual].size() ; i++)
{
int v = adj[atual][i] ;
grau[v]-- ;
if (grau[v] == 0)
{
order.pb(v) ;
}
}
}
return (order.size() == n) ? true : false ;
}
int main ()
{
ios_base::sync_with_stdio(false) ;
cin.tie(NULL) ;
cin >> n >> m ;
for (int i = 1 ; i <= m ; i++)
{
cin >> a >> b ;
grau[a]++ ;
adj[b].pb(a) ;
}
for (int i = 1 ; i <= n ; i++)
{
if (grau[i] == 0)
{
order.pb(i) ;
}
}
if (topological_sort())
{
for (int i = 0 ; i < order.size() ; i++)
{
cout << order[i] << " " ;
}
cout << endl ;
}
else
{
cout << "Impossible\n" ;
}
return 0 ;
}