-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2786_leetcode
More file actions
72 lines (48 loc) · 2.05 KB
/
Copy path2786_leetcode
File metadata and controls
72 lines (48 loc) · 2.05 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
58
59
60
61
62
63
64
65
66
67
68
69
70
class Solution {
public:
typedef pair<int, int> P;
vector<vector<int>> t;
int countWalls(vector<int>& walls, int l, int r) {
int left = lower_bound(begin(walls), end(walls), l) - begin(walls);
int right = upper_bound(begin(walls), end(walls), r) - begin(walls);
return right - left;
}
int solve(vector<int>& walls, vector<P>& roboDist, vector<P>& range, int i, int prevDir) {
if(i == roboDist.size())
return 0;
if(t[i][prevDir] != -1)
return t[i][prevDir];
int leftStart = range[i].first;
if(prevDir == 1) { //prev robot fired bullet rtowards right
leftStart = max(leftStart, range[i-1].second + 1);
}
int leftTake = countWalls(walls, leftStart, roboDist[i].first)
+ solve(walls, roboDist, range, i+1, 0);
int rightTake = countWalls(walls, roboDist[i].first, range[i].second)
+ solve(walls, roboDist, range, i+1, 1);
return t[i][prevDir] = max(leftTake, rightTake);
}
int maxWalls(vector<int>& robots, vector<int>& distance, vector<int>& walls) {
int n = robots.size();
vector<P> roboDist(n);
for (int i = 0; i < n; i++) {
roboDist[i] = {robots[i], distance[i]};
}
sort(begin(roboDist), end(roboDist));
sort(begin(walls), end(walls));
//Prepare range vector for each robot
vector<P> range(n);
for(int i = 0; i < n; i++) {
int pos = roboDist[i].first;
int d = roboDist[i].second;
int leftLimit = (i == 0) ? 1 : roboDist[i-1].first+1;
int rightLimit = (i == n-1) ? 1e9 : roboDist[i+1].first-1;
int L = max(pos - d, leftLimit);
int R = min(pos + d, rightLimit);
range[i] = {L, R};
}
t.assign(n+1, vector<int>(2, -1));
//prev = 0/1 (previious robot hit buttlet to left/right)
return solve(walls, roboDist, range, 0, 0);
}
};