-
Notifications
You must be signed in to change notification settings - Fork 0
/
shortest path.cpp
54 lines (45 loc) · 1.62 KB
/
shortest path.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
47
48
49
50
51
52
53
54
class Solution {
public:
vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {
int n = positions.size();
vector<vector<int>> robots;
for (int i = 0; i < n; ++i) {
robots.push_back({positions[i], healths[i], directions[i], i});
}
sort(robots.begin(), robots.end());
vector<vector<int>> stack;
for (auto& robot : robots) {
if (robot[2] == 'R' || stack.empty() || stack.back()[2] == 'L') {
stack.push_back(robot);
continue;
}
if (robot[2] == 'L') {
bool add = true;
while (!stack.empty() && stack.back()[2] == 'R' && add) {
int last_health = stack.back()[1];
if (robot[1] > last_health) {
stack.pop_back();
robot[1] -= 1;
} else if (robot[1] < last_health) {
stack.back()[1] -= 1;
add = false;
} else {
stack.pop_back();
add = false;
}
}
if (add) {
stack.push_back(robot);
}
}
}
vector<int> result;
sort(stack.begin(), stack.end(), [](vector<int>& a, vector<int>& b) {
return a[3] < b[3];
});
for (auto& robot : stack) {
result.push_back(robot[1]);
}
return result;
}
};