- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- 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.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int findCrossingTime(int n, int k, vector<vector<int>>& time) {4 int ans = 0;5 using P = pair<int, int>;6 7 priority_queue<P> leftBridgeQueue;8 priority_queue<P> rightBridgeQueue;9 10 priority_queue<P, vector<P>, greater<>> leftWorkers;11 priority_queue<P, vector<P>, greater<>> rightWorkers;12 13 for (int i = 0; i < k; ++i)14 leftBridgeQueue.emplace(15 time[i][0] + time[i][2], i);16 17 while (n > 0 || !rightBridgeQueue.empty() || !rightWorkers.empty()) {18 19 while (!leftWorkers.empty() && leftWorkers.top().first <= ans) {20 const int i = leftWorkers.top().second;21 leftWorkers.pop();22 leftBridgeQueue.emplace(23 time[i][0] + time[i][2], i);24 }25 26 while (!rightWorkers.empty() && rightWorkers.top().first <= ans) {27 const int i = rightWorkers.top().second;28 rightWorkers.pop();29 rightBridgeQueue.emplace(30 time[i][0] + time[i][2], i);31 }32 33 if (!rightBridgeQueue.empty()) {34 35 36 37 const int i = rightBridgeQueue.top().second;38 rightBridgeQueue.pop();39 ans += time[i][2];40 leftWorkers.emplace(ans + time[i][3], i);41 } else if (!leftBridgeQueue.empty() && n > 0) {42 43 44 45 46 47 const int i = leftBridgeQueue.top().second;48 leftBridgeQueue.pop();49 ans += time[i][0];50 rightWorkers.emplace(ans + time[i][1], i);51 --n;52 } else {53 54 ans = min(55 !leftWorkers.empty() && n > 0 ? leftWorkers.top().first : INT_MAX,56 !rightWorkers.empty() ? rightWorkers.top().first : INT_MAX);57 }58 }59 60 return ans;61 }62};63