-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfruits-into-baskets-iii.cpp
More file actions
57 lines (45 loc) · 1.19 KB
/
fruits-into-baskets-iii.cpp
File metadata and controls
57 lines (45 loc) · 1.19 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <bits/stdc++.h>
using namespace std;
class Solution {
vector<int> tree;
void update(int p, int L, int R, int pos, int new_val) {
if (L == R) {
tree[p] = new_val;
} else {
const int m = (L + R) / 2;
if (pos <= m)
update(2 * p, L, m, pos, new_val);
else
update(2 * p + 1, m + 1, R, pos, new_val);
tree[p] = max(tree[2 * p], tree[2 * p + 1]);
}
}
int first_equal_or_greater(const int n, const int val) {
int p = 1;
if (tree[p] < val) return -1;
int l = 0, r = n - 1;
while (l != r) {
const int m = (l + r) / 2;
if (tree[2 * p] >= val)
r = m, p = 2 * p;
else
l = m + 1, p = 2 * p + 1;
}
return l;
}
public:
int numOfUnplacedFruits(const vector<int>& fruits, const vector<int>& baskets) {
const int n = fruits.size();
tree.assign(n * 4, 0);
for (size_t i = 0; i < baskets.size(); i++) {
update(1, 0, n - 1, i, baskets[i]);
}
int ans = 0;
for (size_t i = 0; i < fruits.size(); i++) {
const int idx = first_equal_or_greater(n, fruits[i]);
ans += idx == -1;
if (idx != -1) update(1, 0, n - 1, idx, 0);
}
return ans;
}
};