Problem solution · C++

Time to Cross a Bridge

Time to Cross a Bridge: a C++ solution using binary search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Binary search
Source
walkccc LeetCode Solutions
Length
63 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Binary search

For Time to Cross a Bridge, the implementation exploits a monotonic condition to discard half of the remaining search space after every check.

  1. Identify the ordered answer range or sorted search domain.
  2. Write a predicate whose truth changes only once.
  3. Move the appropriate boundary after each midpoint check and return the final feasible position.

Code notes

  • 63 lines of C++ from the credited upstream file 2532.cpp.
  • The implementation visibly relies on sequence storage, work queue.
  • 4 loop blocks detected.

Complexity

Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeTime to Cross a Bridge · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  int findCrossingTime(int n, int k, vector<vector<int>>& time) {    int ans = 0;    using P = pair<int, int>;    // (leftToRight + rightToLeft, i)    priority_queue<P> leftBridgeQueue;    priority_queue<P> rightBridgeQueue;    // (time to be idle, i)    priority_queue<P, vector<P>, greater<>> leftWorkers;    priority_queue<P, vector<P>, greater<>> rightWorkers;     for (int i = 0; i < k; ++i)      leftBridgeQueue.emplace(          /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i);     while (n > 0 || !rightBridgeQueue.empty() || !rightWorkers.empty()) {      // Idle left workers get on the left bridge.      while (!leftWorkers.empty() && leftWorkers.top().first <= ans) {        const int i = leftWorkers.top().second;        leftWorkers.pop();        leftBridgeQueue.emplace(            /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i);      }      // Idle right workers get on the right bridge.      while (!rightWorkers.empty() && rightWorkers.top().first <= ans) {        const int i = rightWorkers.top().second;        rightWorkers.pop();        rightBridgeQueue.emplace(            /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i);      }       if (!rightBridgeQueue.empty()) {        // If the bridge is free, the worker waiting on the right side of the        // bridge gets to cross the bridge. If more than one worker is waiting        // on the right side, the one with the lowest efficiency crosses first.        const int i = rightBridgeQueue.top().second;        rightBridgeQueue.pop();        ans += /*rightToLeft*/ time[i][2];        leftWorkers.emplace(ans + /*putNew*/ time[i][3], i);      } else if (!leftBridgeQueue.empty() && n > 0) {        // If the bridge is free and no worker is waiting on the right side, and        // at least one box remains at the old warehouse, the worker on the left        // side of the river gets to cross the bridge. If more than one worker        // is waiting on the left side, the one with the lowest efficiency        // crosses first.        const int i = leftBridgeQueue.top().second;        leftBridgeQueue.pop();        ans += /*leftToRight*/ time[i][0];        rightWorkers.emplace(ans + /*pickOld*/ time[i][1], i);        --n;      } else {        // Advance the time of the last crossing worker.        ans = min(            !leftWorkers.empty() && n > 0 ? leftWorkers.top().first : INT_MAX,            !rightWorkers.empty() ? rightWorkers.top().first : INT_MAX);      }    }     return ans;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗