1
- using pii = pair<int , int >;
2
-
3
- class Solution {
4
- public:
5
- int minNumberOfSemesters (int n, vector<vector<int >>& relations, int k) {
6
- vector<int > d (n + 1 );
7
- for (auto & e : relations) {
8
- d[e[1 ]] |= 1 << e[0 ];
9
- }
10
- queue<pii> q;
11
- q.push ({0 , 0 });
12
- unordered_set<int > vis{{0 }};
13
- while (!q.empty ()) {
14
- auto [cur, t] = q.front ();
15
- q.pop ();
16
- if (cur == (1 << (n + 1 )) - 2 ) {
17
- return t;
18
- }
19
- int nxt = 0 ;
20
- for (int i = 1 ; i <= n; ++i) {
21
- if ((cur & d[i]) == d[i]) {
22
- nxt |= 1 << i;
23
- }
24
- }
25
- nxt ^= cur;
26
- if (__builtin_popcount (nxt) <= k) {
27
- if (!vis.count (nxt | cur)) {
28
- vis.insert (nxt | cur);
29
- q.push ({nxt | cur, t + 1 });
30
- }
31
- } else {
32
- int x = nxt;
33
- while (nxt) {
34
- if (__builtin_popcount (nxt) == k && !vis.count (nxt | cur)) {
35
- vis.insert (nxt | cur);
36
- q.push ({nxt | cur, t + 1 });
37
- }
38
- nxt = (nxt - 1 ) & x;
39
- }
40
- }
41
- }
42
- return 0 ;
43
- }
1
+ class Solution {
2
+ public:
3
+ int minNumberOfSemesters (int n, vector<vector<int >>& relations, int k) {
4
+ vector<int > d (n + 1 );
5
+ for (auto & e : relations) {
6
+ d[e[1 ]] |= 1 << e[0 ];
7
+ }
8
+ queue<pair<int , int >> q;
9
+ q.push ({0 , 0 });
10
+ unordered_set<int > vis{{0 }};
11
+ while (!q.empty ()) {
12
+ auto [cur, t] = q.front ();
13
+ q.pop ();
14
+ if (cur == (1 << (n + 1 )) - 2 ) {
15
+ return t;
16
+ }
17
+ int nxt = 0 ;
18
+ for (int i = 1 ; i <= n; ++i) {
19
+ if ((cur & d[i]) == d[i]) {
20
+ nxt |= 1 << i;
21
+ }
22
+ }
23
+ nxt ^= cur;
24
+ if (__builtin_popcount (nxt) <= k) {
25
+ if (!vis.count (nxt | cur)) {
26
+ vis.insert (nxt | cur);
27
+ q.push ({nxt | cur, t + 1 });
28
+ }
29
+ } else {
30
+ int x = nxt;
31
+ while (nxt) {
32
+ if (__builtin_popcount (nxt) == k && !vis.count (nxt | cur)) {
33
+ vis.insert (nxt | cur);
34
+ q.push ({nxt | cur, t + 1 });
35
+ }
36
+ nxt = (nxt - 1 ) & x;
37
+ }
38
+ }
39
+ }
40
+ return 0 ;
41
+ }
44
42
};
0 commit comments