Leetcode Problem 2532. Time to Cross a Bridge

2532. Time to Cross a Bridge

Leetcode Solutions

Heap-Based Simulation

  1. Initialize a min-heap left with pairs [-t[0]-t[2], -i] for each worker i, where t is the time array for that worker. This heap sorts workers by their efficiency in descending order.
  2. Initialize an empty min-heap right for workers on the right bank.
  3. Initialize an empty min-heap save for events when workers will be ready to cross the bridge or finish putting boxes.
  4. Set cnt to 0 to count the number of boxes moved, note to 0 to count the number of workers sent to the right bank, and tmstamp to 0 to track the current time.
  5. While cnt is less than n, repeat the following steps: a. If both left and right are empty and the earliest event in save is in the future, advance tmstamp to that event's time. b. Process all events in save that are due by tmstamp, moving workers to the appropriate bank heaps. c. If note equals n or right is not empty, let the least efficient worker on the right bank cross the bridge, update tmstamp, and push the event of them being ready to save. d. If right is empty and note is less than n, let the least efficient worker on the left bank cross to the right, update tmstamp, and push the event of them being ready to save. e. Increment note if a worker was sent to the right bank.
  6. Return tmstamp as the time when the last worker reaches the left bank.
UML Thumbnail

Simulation with Priority Queues and Sets

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...