-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.cpp
42 lines (42 loc) · 1.29 KB
/
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
34
35
36
37
38
39
40
41
42
class Solution {
public:
int minNumberOfSemesters(int n, vector<vector<int>>& relations, int k) {
vector<int> d(n + 1);
for (auto& e : relations) {
d[e[1]] |= 1 << e[0];
}
queue<pair<int, int>> q;
q.push({0, 0});
unordered_set<int> vis{{0}};
while (!q.empty()) {
auto [cur, t] = q.front();
q.pop();
if (cur == (1 << (n + 1)) - 2) {
return t;
}
int nxt = 0;
for (int i = 1; i <= n; ++i) {
if ((cur & d[i]) == d[i]) {
nxt |= 1 << i;
}
}
nxt ^= cur;
if (__builtin_popcount(nxt) <= k) {
if (!vis.count(nxt | cur)) {
vis.insert(nxt | cur);
q.push({nxt | cur, t + 1});
}
} else {
int x = nxt;
while (nxt) {
if (__builtin_popcount(nxt) == k && !vis.count(nxt | cur)) {
vis.insert(nxt | cur);
q.push({nxt | cur, t + 1});
}
nxt = (nxt - 1) & x;
}
}
}
return 0;
}
};