-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathmaximum-number-of-points-from-grid-queries.cpp
46 lines (44 loc) · 1.71 KB
/
maximum-number-of-points-from-grid-queries.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
43
44
45
46
// Time: O((m * n + q) * log(m * n))
// Space: O(m * n)
// bfs, heap, prefix sum, binary search
class Solution {
public:
vector<int> maxPoints(vector<vector<int>>& grid, vector<int>& queries) {
static const vector<pair<int, int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<tuple<int, int, int>>> min_heap;
min_heap.emplace(grid[0][0], 0, 0);
vector<vector<bool>> lookup(size(grid), vector<bool>(size(grid[0])));
lookup[0][0] = true;
unordered_map<int, int> cnt;
int mx = 0;
while (!empty(min_heap)) {
const auto [curr, i, j] = min_heap.top(); min_heap.pop();
mx = max(mx, curr);
++cnt[mx];
for (const auto& [di, dj] : directions) {
const int ni = i + di, nj = j + dj;
if (!(0 <= ni && ni < size(grid) &&
0 <= nj && nj < size(grid[0]) &&
!lookup[ni][nj])) {
continue;
}
lookup[ni][nj] = true;
min_heap.emplace(grid[ni][nj], ni, nj);
}
}
vector<int> vals;
for (const auto& [k, _] : cnt) {
vals.emplace_back(k);
}
sort(begin(vals), end(vals));
vector<int> prefix(size(vals) + 1);
for (int i = 0; i < size(vals); ++i) {
prefix[i + 1] = prefix[i] + cnt[vals[i]];
}
vector<int> result(size(queries));
for (int i = 0; i < size(queries); ++i) {
result[i] = prefix[distance(cbegin(vals), lower_bound(cbegin(vals), cend(vals), queries[i]))];
}
return result;
}
};