-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2751.RobotCollisions.cpp
More file actions
84 lines (70 loc) · 2.04 KB
/
2751.RobotCollisions.cpp
File metadata and controls
84 lines (70 loc) · 2.04 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class Solution {
public:
struct Data {
int m_position, m_index;
const bool operator <(const Data& other) const {
return m_position < other.m_position;
}
};
vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {
// Speed thingies.
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
// Calculation variables.
const int n = min(positions.size(), min(healths.size(), directions.size()));
vector<int> remaining;
// Sort positions.
vector<Data> sortedData;
for (int i = 0; i < n; i++)
sortedData.push_back({ positions[i], i });
sort(sortedData.begin(), sortedData.end());
// Stack based approach, working left to right.
stack<int> workingStack;
for (int i = 0; i < n; i++) {
// Get true active index.
const int selfIndex = sortedData[i].m_index;
if (directions[selfIndex] == 'R') {
// Add right-facing to stack to stop left-facing robots.
workingStack.push(selfIndex);
continue;
}
// All happy days if none on stack.
if (workingStack.empty()) {
remaining.emplace_back(selfIndex);
continue;
}
// Work through stack.
bool alive = true;
while (!workingStack.empty()) {
const int otherIndex = workingStack.top();
if (healths[otherIndex] == healths[selfIndex]) {
// Destroy both robots.
alive = false;
workingStack.pop();
break;
} else if (healths[otherIndex] > healths[selfIndex]) {
// Destroy self.
healths[otherIndex]--;
alive = false;
break;
}
// Destroy other.
healths[selfIndex]--;
workingStack.pop();
}
// Left-facing destroyed all robots to the left.
if (alive) remaining.emplace_back(selfIndex);
}
// Get indices from stack too.
while (!workingStack.empty()) {
remaining.emplace_back(workingStack.top());
workingStack.pop();
}
// Convert indices to sorted health.
sort(remaining.begin(), remaining.end());
for (int i = 0; i < remaining.size(); i++)
remaining[i] = healths[remaining[i]];
return remaining;
}
};