-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path210.cpp
More file actions
29 lines (29 loc) · 924 Bytes
/
Copy path210.cpp
File metadata and controls
29 lines (29 loc) · 924 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
class Solution {
public:
vector<int> findOrder(int n, vector<pair<int, int>> &prerequisites) {
vector<unordered_set<int>> graph(n, unordered_set<int>());
vector<int> in_degree(n, 0);
vector<int> seq;
for (int i = 0; i < prerequisites.size(); ++i)
graph[prerequisites[i].second].insert(prerequisites[i].first);
for (int i = 0; i < n; ++i)
for (auto in:graph[i])
++in_degree[in];
for (int i = 0; i < n; ++i) {
int j = 0;
while (j < n) {
if (in_degree[j] == 0)
break;
++j;
}
if (j == n)
continue;
seq.push_back(j);
in_degree[j] = -1;
for (auto &post:graph[j]) {
--in_degree[post];
}
}
return seq.size() == n ? seq : vector<int>{};
}
};