-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCourse_Schedule.cpp
More file actions
58 lines (45 loc) · 951 Bytes
/
Course_Schedule.cpp
File metadata and controls
58 lines (45 loc) · 951 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
47
48
49
50
51
52
53
54
55
56
57
58
#include <bits/stdc++.h>
using namespace std;
/*
Topological sort using Kahn's Algorithm
*/
int main() {
int n, m;
cin >> n >> m;
map<int, vector<int>> adj;
vector<int> indegree(n + 1, 0);
while (m--) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
indegree[b]++;
}
queue<int> q;
for (int i = 1; i <= n; i++) {
if (indegree[i] == 0)
q.push(i);
}
if (q.empty()) {
cout << "IMPOSSIBLE";
return 0;
}
vector<int> order;
while (!q.empty()) {
int cur = q.front();
q.pop();
order.push_back(cur);
for (int next : adj[cur]) {
indegree[next]--;
if (indegree[next] == 0)
q.push(next);
}
}
if (order.size() != n) {
cout << "IMPOSSIBLE";
return 0;
}
for (int v : order) {
cout << v << " ";
}
return 0;
}