Problem Description
Given n boxes and k workers with their individual times for crossing the bridge (to the right warehouse and back to the left), picking up a box, and putting the box down, simulate the process to determine when the last box is delivered to the left warehouse. Workers are dispatched according to specific priority rules based on their “efficiency” (the sum of left and right crossing times) and an extra rule that prevents sending more workers from the left if there are already enough on the right to handle the remaining boxes.
Key Insights
- This is an event simulation problem that must handle workers’ movements between two warehouses.
- Use two sets of priority queues (heaps) – one for workers waiting on the left side and one for those waiting on the right – while keeping track of their “ready time.”
- The “least efficient” workers (those with a larger sum of left+right times, and in a tie, the ones with a higher index) are prioritized when the bridge is available.
- Be careful to only send a worker from the left if there are still boxes that are not “covered” by workers already dispatched to the right.
- Time advances to either the next available ready event or when a crossing finishes.
Space and Time Complexity
Time Complexity: O((n + k) * log k) – each event (dispatch, pick, cross, and put) is processed with heap operations. Space Complexity: O(k) – we maintain heaps for up to k workers.
Solution
We simulate the process using two main types of heaps:
- Two time-sorted event-queues (min-heaps) for each side (left and right) that hold events when workers become available.
- Two “ready” heaps (max-heaps, simulated via negating the efficiency values) that order workers according to the “least efficient” rule among those whose events are ready at the current time.
Each worker’s cycle is simulated in steps:
- From the left side: a worker crosses the bridge taking his “right” time; upon arrival, he performs his “pick” action and then is scheduled to wait on the right.
- From the right side: when a worker is waiting (i.e. already picked a box), he crosses back with the box (taking his “left” time). This completes the delivery – the crossing finish is recorded as a candidate answer. Afterward, he performs his “put” action and then is scheduled as available on the left side.
A key detail is that we do not dispatch a worker from the left side (even if he is available) when there are already enough workers on the right to handle the remaining boxes (i.e. workersOnRight ≥ remainingBoxes).
We iterate until we have delivered all n boxes. The final answer is the time at which the last worker finishes the crossing from right to left.