forked from shivaylamba/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
topological_sort.cpp
88 lines (71 loc) · 1.31 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
# include <bits/stdc++.h>
#define flash ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL)
#define endl '\n'
#define ll long long int
#include <tr1/unordered_map>
#define ld long double
#define pb push_back
#define mp make_pair
#define MOD 1000000007
#define f(i,a,b) for(long long i=a;i<b;i++)
#define all(c) (c).begin(),(c).end()
#include <map>
using namespace std;
vector <int> vect[100];
bool vis[100];
int sol[100];
void ini()
{
for(int i=0;i<10;i++)
{
vis[i]=false;
}
}
int dfs(int i,int j)
{
vis[j]=true;
for(int k=0;k<vect[j].size();k++)
{
if(vis[vect[j][k]]==false)
{
i=dfs(i,vect[j][k]);
}
}
sol[i]=j;
return i-1;
}
void topo(int n)
{
int i=n-1;
for(int j=1;j<=n;j++)
{
if(vis[j]==false)
{
i=dfs(i,j);
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("C:\\Users\\user\\Desktop\\coding problems\\in.txt","r",stdin);
freopen("C:\\Users\\user\\Desktop\\coding problems\\output.txt","w",stdout);
#endif
flash;
///////////////////////////////////////////////////////////////////////////////////////
int n,e;
cin>>n>>e;
for(int i=0;i<e;i++)
{
int x,y;
cin>>x>>y;
vect[x].push_back(y);
}
topo(n);
for(int i=0;i<n;i++)
{
cout<<sol[i]<<" ";
}
///////////////////////////////////////////////////////////////////////////////////////
return 0;
}