Skip to content

Commit 8ee2cfe

Browse files
authored
Update 1494-parallel-courses-ii.js
1 parent c5d45d8 commit 8ee2cfe

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

1494-parallel-courses-ii.js

+52
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,55 @@
1+
/**
2+
* @param {number} n
3+
* @param {number[][]} relations
4+
* @param {number} k
5+
* @return {number}
6+
*/
7+
const minNumberOfSemesters = function(n, relations, k) {
8+
const limit = (1 << n)
9+
const dp = Array(limit).fill(Number.MAX_SAFE_INTEGER)
10+
const preCourse = Array(n).fill(0)
11+
const preState = Array(limit).fill(0)
12+
13+
for(const [s, d] of relations) {
14+
preCourse[d - 1] |= (1 << (s - 1))
15+
}
16+
for(let state = 0; state < limit; state++) {
17+
for(let i = 0; i < n; i++) {
18+
if(state & (1 << i)) {
19+
preState[state] |= preCourse[i]
20+
}
21+
}
22+
if(preState[state] === 0 && bitCnt(state) <= k) dp[state] = 1
23+
}
24+
dp[0] = 0
25+
for(let state = 1; state < limit; state++) {
26+
for(let sub = state; sub >= 0; sub = (sub - 1) & state) {
27+
if(
28+
bitCnt(state) - bitCnt(sub) <= k &&
29+
((preState[state] & sub) === preState[state])
30+
) {
31+
// console.log('d', state, sub, dp)
32+
dp[state] = Math.min(dp[state], dp[sub] + 1)
33+
}
34+
if(sub === 0) break
35+
}
36+
}
37+
38+
// console.log(limit)
39+
return dp[limit - 1]
40+
};
41+
42+
function bitCnt(num) {
43+
let res = 0
44+
while(num) {
45+
res++
46+
num &= (num - 1)
47+
}
48+
return res
49+
}
50+
51+
// another
52+
153
/**
254
* @param {number} n
355
* @param {number[][]} dependencies

0 commit comments

Comments
 (0)