|
| 1 | +//////////////////////////////////////////////Template///////////////////////////////////////////////////////////// |
| 2 | +function Bisect() { |
| 3 | + return { insort_right, insort_left, bisect_left, bisect_right } |
| 4 | + function insort_right(a, x, lo = 0, hi = null) { |
| 5 | + lo = bisect_right(a, x, lo, hi) |
| 6 | + a.splice(lo, 0, x) |
| 7 | + } |
| 8 | + function bisect_right(a, x, lo = 0, hi = null) { |
| 9 | + // > upper_bound |
| 10 | + if (lo < 0) throw new Error('lo must be non-negative') |
| 11 | + if (hi == null) hi = a.length |
| 12 | + while (lo < hi) { |
| 13 | + let mid = parseInt((lo + hi) / 2) |
| 14 | + x < a[mid] ? (hi = mid) : (lo = mid + 1) |
| 15 | + } |
| 16 | + return lo |
| 17 | + } |
| 18 | + function insort_left(a, x, lo = 0, hi = null) { |
| 19 | + lo = bisect_left(a, x, lo, hi) |
| 20 | + a.splice(lo, 0, x) |
| 21 | + } |
| 22 | + function bisect_left(a, x, lo = 0, hi = null) { |
| 23 | + // >= lower_bound |
| 24 | + if (lo < 0) throw new Error('lo must be non-negative') |
| 25 | + if (hi == null) hi = a.length |
| 26 | + while (lo < hi) { |
| 27 | + let mid = parseInt((lo + hi) / 2) |
| 28 | + a[mid] < x ? (lo = mid + 1) : (hi = mid) |
| 29 | + } |
| 30 | + return lo |
| 31 | + } |
| 32 | +} |
| 33 | +/** |
| 34 | + * @param {number[]} tasks |
| 35 | + * @param {number[]} workers |
| 36 | + * @param {number} pills |
| 37 | + * @param {number} strength |
| 38 | + * @return {number} |
| 39 | + */ |
| 40 | +const maxTaskAssign = function(tasks, workers, pills, strength) { |
| 41 | + tasks.sort((a, b) => a - b) |
| 42 | + workers.sort((a, b) => b - a) |
| 43 | + const m = tasks.length, n = workers.length |
| 44 | + const { min, floor } = Math |
| 45 | + let l = 0, r = min(n, m) |
| 46 | + while (l < r) { |
| 47 | + const mid = r - floor((r - l) / 2) |
| 48 | + if (check(mid)) l = mid |
| 49 | + else r = mid - 1 |
| 50 | + } |
| 51 | + |
| 52 | + return l |
| 53 | + |
| 54 | + function check(k){ |
| 55 | + const wArr = workers.slice(0, k), tArr = tasks.slice(0, k) |
| 56 | + let tries = pills, bs = new Bisect() |
| 57 | + wArr.reverse() |
| 58 | + tArr.reverse() |
| 59 | + |
| 60 | + for (let elem of tArr) { |
| 61 | + const place = bs.bisect_left(wArr, elem) |
| 62 | + if (place < wArr.length) { |
| 63 | + wArr.pop() |
| 64 | + } else if (tries > 0) { |
| 65 | + const place2 = bs.bisect_left(wArr, elem - strength) |
| 66 | + if (place2 < wArr.length) { |
| 67 | + wArr.splice(place2, 1) |
| 68 | + tries -= 1 |
| 69 | + } |
| 70 | + } else return false |
| 71 | + } |
| 72 | + |
| 73 | + return wArr.length === 0 |
| 74 | + } |
| 75 | +}; |
0 commit comments