-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_queue3_truck_passing_bridge.py
More file actions
35 lines (27 loc) · 1.25 KB
/
stack_queue3_truck_passing_bridge.py
File metadata and controls
35 lines (27 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from collections import deque
def solution(bridge_length, weight, truck_weights):
truck_len = len(truck_weights)
wait, inbridge, outbridge = deque(truck_weights), deque(), deque()
timer, cur_bridge_weight = 1, 0
while not len(outbridge) == truck_len:
if wait:
enter_truck = wait.popleft()
#if bridge available(current bridge weight + willing to enter truck)
if weight >= cur_bridge_weight + enter_truck:
#access
inbridge.append([enter_truck, 0]) #enter truck weight & start timer
cur_bridge_weight += enter_truck # current bridge weight is increased
else:
# retore at wait
wait.appendleft(enter_truck)
for truck in list(inbridge):
truck[1] += 1
if truck[1] == bridge_length: # if time to get out
getout_truck = inbridge.popleft()
cur_bridge_weight -= getout_truck[0]
outbridge.append(getout_truck)
timer += 1
return timer
print(solution(2, 10, [7,4,5,6])) #8
print(solution(100, 100, [10])) #101
print(solution(100, 100, [10,10,10,10,10,10,10,10,10,10])) #110