-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopo_Sort.cpp
More file actions
46 lines (36 loc) · 783 Bytes
/
Topo_Sort.cpp
File metadata and controls
46 lines (36 loc) · 783 Bytes
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 ;
typedef vector <int> vi ;
vi topo ;
vector <vi> adj ;
bool vis [35000] ;
void dfs(int u){
vis[u] = true ;
for ( int i = 0 ; i <adj[u].size() ; i++)
if(!vis[ adj[u][i] ] )
dfs( adj[u][i]);
topo.push_back(u) ;
}
int main(){
memset ( vis , false ,sizeof vis);
int n , m , i, j ,x , y;
cin >> n >> m ;
adj.assign( n+1 , vi());
for ( i = 0 ; i < m ; i++){
cin >> x >> y ;
adj[y].push_back(x) ;
}
for ( i = 1 ; i <= n ; i++){
if ( !vis[i] )
dfs(i);
}
reverse ( topo.begin() , topo.end() );
// cout << topo.size() << endl;
if ( topo.size() != n ){
cout <<"-1\n" ; return 0 ;
}
for ( i = 0 ; i < n ; i++){
cout <<topo[i] <<" ";
}
return 0 ;
}