forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
33 lines (33 loc) · 873 Bytes
/
Solution.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
class Solution {
public:
int minimumSemesters(int n, vector<vector<int>>& relations) {
vector<vector<int>> g(n);
vector<int> indeg(n);
for (auto& r : relations) {
int prev = r[0] - 1, nxt = r[1] - 1;
g[prev].push_back(nxt);
++indeg[nxt];
}
queue<int> q;
for (int i = 0; i < n; ++i) {
if (indeg[i] == 0) {
q.push(i);
}
}
int ans = 0;
while (!q.empty()) {
++ans;
for (int k = q.size(); k; --k) {
int i = q.front();
q.pop();
--n;
for (int& j : g[i]) {
if (--indeg[j] == 0) {
q.push(j);
}
}
}
}
return n == 0 ? ans : -1;
}
};