-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopologicalsort.cpp
More file actions
54 lines (51 loc) · 1 KB
/
Topologicalsort.cpp
File metadata and controls
54 lines (51 loc) · 1 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
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <sstream>
#include <set>
#include <map>
#include <queue>
#include <stack>
#define MAXN 100
using namespace std;
int n,m ;
vector < int > g [MAXN] ;
bool used [ MAXN ] ;
vector < int > ans ;
void dfs ( int v ) {
//cout<<"YO"<<endl;
used [ v ] = true ;
for ( size_t i = 0 ; i < g [ v ] . size ( ) ; ++ i ) {
int to = g [ v ] [ i ] ;
if ( ! used [ to ] )
dfs ( to ) ;
}
ans. push_back ( v ) ;
}
void topological_sort ( ) {
for ( int i = 0 ; i < n ; ++ i )
used [ i ] = false ;
ans. clear ( ) ;
//cout<<"YO";
for ( int i = 0 ; i < n ; ++ i )
if ( ! used [ i ] )
dfs ( i ) ;
reverse ( ans. begin ( ) , ans. end ( ) ) ;
}
int main()
{
scanf("%d %d",&n,&m);
while(m--){
int a,b;
scanf("%d %d",&a,&b);
g[a-1].push_back(b-1);
}
topological_sort();
for(int i=0;i<ans.size();i++)
{
cout<<ans[i]+1<<" ";
}
}