Skip to content

Commit 6535e5b

Browse files
authored
Create 2532.Time-to-Cross-a-Bridge.cpp
1 parent 9396d48 commit 6535e5b

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
using PII = pair<int,int>;
2+
class Solution {
3+
public:
4+
int findCrossingTime(int n, int k, vector<vector<int>>& time)
5+
{
6+
priority_queue<PII, vector<PII>, greater<>>leftArrive;
7+
priority_queue<PII, vector<PII>, greater<>>rightArrive;
8+
for (int i=0; i<k; i++)
9+
leftArrive.push({0, i});
10+
11+
int nextFree = 0;
12+
priority_queue<PII>leftWait;
13+
priority_queue<PII>rightWait;
14+
15+
int ret = 0;
16+
int count = 0;
17+
int taken = 0;
18+
19+
while (count < n)
20+
{
21+
while (!leftArrive.empty() && leftArrive.top().first <= nextFree)
22+
{
23+
auto [arriveTime, id] = leftArrive.top();
24+
leftArrive.pop();
25+
leftWait.push({time[id][0]+time[id][2], id});
26+
}
27+
while (!rightArrive.empty() && rightArrive.top().first <= nextFree)
28+
{
29+
auto [arriveTime, id] = rightArrive.top();
30+
rightArrive.pop();
31+
rightWait.push({time[id][0]+time[id][2], id});
32+
}
33+
34+
if (leftWait.empty() && rightWait.empty())
35+
{
36+
int t1 = leftArrive.empty() ? INT_MAX : leftArrive.top().first;
37+
int t2 = rightArrive.empty() ? INT_MAX : rightArrive.top().first;
38+
nextFree = min(t1, t2);
39+
continue;
40+
}
41+
42+
if (!rightWait.empty()) // R -> L
43+
{
44+
auto [_, id] = rightWait.top();
45+
rightWait.pop();
46+
nextFree += time[id][2];
47+
leftArrive.push({nextFree+time[id][3], id});
48+
49+
count++;
50+
ret = max(ret, nextFree);
51+
}
52+
else if (!leftWait.empty()) // L -> R
53+
{
54+
if (taken == n)
55+
{
56+
while (!leftWait.empty())
57+
leftWait.pop();
58+
} else
59+
{
60+
auto [_, id] = leftWait.top();
61+
leftWait.pop();
62+
nextFree += time[id][0];
63+
rightArrive.push({nextFree+time[id][1], id});
64+
taken++;
65+
}
66+
}
67+
}
68+
69+
return nextFree;
70+
}
71+
};

0 commit comments

Comments
 (0)