../ Competitive Programming
-rw-r--r--aguang1.9 KiB1 min read

Leet Code Daily 2024-07-13 - Robot Collisions

Solution

Sort & Stack.

Code

c++
struct robot {
    int position;
    int health;
    char direction;
};

class Solution {
public:
    vector<int> survivedRobotsHealths(vector<int>& positions,
                                      vector<int>& healths, string directions) {

        const int n = positions.size();

        vector<robot> robots;
        for (int i = 0; i < n; i++) {
            robots.push_back(robot{
                .position = positions[i],
                .health = healths[i],
                .direction = directions[i],
            });
        }
        sort(robots.begin(), robots.end(),
             [](auto& x, auto& y) { return x.position < y.position; });

        stack<robot> stack;
        for (auto& robot : robots) {
            if (robot.direction == 'R') {
                stack.push(robot);
                continue;
            }
            while (!stack.empty() && stack.top().direction == 'R' &&
                   stack.top().health < robot.health) {
                robot.health--;
                stack.pop();
            }
            if (!stack.empty() && stack.top().direction == 'R') {
                if (stack.top().health == robot.health) {
                    stack.pop();
                } else {
                    stack.top().health--;
                }
            } else {
                stack.push(robot);
            }
        }

        unordered_map<int, int> health_map;
        for (; !stack.empty(); stack.pop()) {
            health_map[stack.top().position] = stack.top().health;
        }

        vector<int> ret;
        for (int i = 0; i < n; i++) {
            auto ptr = health_map.find(positions[i]);
            if (ptr != health_map.end()) {
                ret.push_back(ptr->second);
            }
        }
        return ret;
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window