[LeetCode] Robot Collisions

2751. Robot Collisions

There are n 1-indexed robots, each having a position on a line, health, and movement direction.

You are given 0-indexed integer arrays positions, healths, and a string directions (directions[i] is either ‘L’ for left or ‘R’ for right). All integers in positions are unique.

All robots start moving on the line simultaneously at the same speed in their given directions. If two robots ever share the same position while moving, they will collide.

If two robots collide, the robot with lower health is removed from the line, and the health of the other robot decreases by one. The surviving robot continues in the same direction it was going. If both robots have the same health, they are both removed from the line.

Your task is to determine the health of the robots that survive the collisions, in the same order that the robots were given, i.e. final heath of robot 1 (if survived), final health of robot 2 (if survived), and so on. If there are no survivors, return an empty array.

Return an array containing the health of the remaining robots (in the order they were given in the input), after no further collisions can occur.

Note: The positions may be unsorted.

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
struct Robot {
long long ord, pos, hp;
char dir;
};
class Solution {
public:
vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {
deque<Robot> A;
for(int i = 0; i < positions.size(); i++) {
A.push_back({i,positions[i], healths[i], directions[i]});
}
sort(begin(A), end(A), [](auto a, auto b) {
return a.pos < b.pos;
});
map<long long, long long> mp;
deque<Robot> r;
while(A.size()) {
while(A.size() and A.front().dir == 'L') {
mp[A.front().ord] = A.front().hp;
A.pop_front();
}
while(A.size() and A.back().dir == 'R') {
mp[A.back().ord] = A.back().hp;
A.pop_back();
}
while(A.size() and A.front().dir == 'R') {
r.push_back(A.front()); A.pop_front();
}
if(A.size()) {
while(r.size() and A.size() and A.front().dir == 'L') {
if(r.back().hp == A.front().hp) {
r.pop_back(); A.pop_front();
} else if(r.back().hp > A.front().hp) {
A.pop_front();
r.back().hp -= 1;
cout<<r.back().hp<<endl;
} else {
r.pop_back();
A.front().hp -= 1;
}
}
}
}
while(r.size()) {
mp[r.back().ord] = r.back().hp;
r.pop_back();
}
vector<int> res;
for(auto [k,v] : mp) res.push_back(v);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/25/PS/LeetCode/robot-collisions/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.