-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTopologicalSort.cpp
63 lines (53 loc) · 1.01 KB
/
TopologicalSort.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
/*
Topological Sort, DFS method
Ali and Koosha, You should prove correctness of this algorithm for next session :D :)
*/
#include <iostream>
#include <vector>
using namespace std;
const int MAXN = 1000 * 100;
vector<int> adj[MAXN], ans;
bool mark[MAXN];
int n, m, in_degree[MAXN];
void dfs(int v);
bool check_valid();
int main(){
cin >> n >> m;
for(int i = 0; i < n; i++){
int u, v;
adj[u].push_back(v);
in_degree[v]++;
}
for(int i = 1; i <= n; i++)
if(!mark[i])
dfs(i);
if(check_valid()){
for(int i = 0; i < ans.size(); i++)
cout << ans[i] << ' ';
cout << endl;
}
else
cout << "There's no topological sort !"
return 0;
}
void dfs(int v){
mark[v] = true;
for(int i = 0; i < adj[v].size(); i++){
int u = adj[v][i];
if(!mark[u])
dfs(u);
}
ans.push_back(v);
}
bool check_valid(){
for(int i = 0; i < ans.size(); i++){
int v = ans[i];
if(in_degree[v] != 0)
return false;
for(int j = 0; j < adj[v].size(); j++){
int u = adj[v][j];
in_degree[u]--;
}
}
return true;
}