-
Notifications
You must be signed in to change notification settings - Fork 0
/
TopSort.cpp
72 lines (58 loc) · 1.02 KB
/
TopSort.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
/*
* Topological Sort (bfs approach)
* @author Amirul Islam (shiningfalsh)
_
_|_ o._ o._ __|_| _. _|_
_>| ||| ||| |(_|| |(_|_>| |
_|
*/
#include <bits/stdc++.h>
using namespace std;
const int mx = 1e3;
int vis[mx];
vector <int> graph[mx];
void bfs(int node) {
queue <int> q;
for (int i = 1; i <= node; i++) {
if (vis[i] == 0) {
q.push(i);
}
}
while (!q.empty()) {
int u = q.front();
q.pop();
cout << u << " ";
for (int i = 0; i < graph[u].size(); i++) {
int v = graph[u][i];
vis[v]--;
if (vis[v] == 0) {
q.push(v);
}
}
}
}
int main() {
freopen("in", "r", stdin);
int node, edge, u, v;
cin >> node >> edge;
while (edge--) {
cin >> u >> v;
graph[u].push_back(v);
vis[v]++;
}
bfs(node);
cout << "\n";
return 0;
}
/*
Input:
-----
5 4
1 2
2 3
1 3
1 5
Output:
------
1 4 2 5 3
*/