출처 https://programmers.co.kr/learn/courses/30/lessons/42583?language=python3
모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지 알아내야 한다.
트럭 움직임 : 1 / 1초
다리 길이 : bridge_length
다리가 견디는 무게 : weight
(트럭이 다리에 완전히 오르지 않은 경우, 이 트럭의 무게는 고려하지 않는다.)
def solution(bridge_length, weight, truck_weights):
count = 0
on_bridge = []
left_bridge = []
while on_bridge or truck_weights:
count += 1
if len(on_bridge) == 0:
on_bridge.append(truck_weights.pop(0))
left_bridge.append(bridge_length)
else:
left_bridge = list(map(lambda x:x-1, left_bridge))
if left_bridge[0]==0:
left_bridge.pop(0)
on_bridge.pop(0)
for i in truck_weights:
if sum(on_bridge) + i <= weight:
on_bridge.append(truck_weights.pop(0))
left_bridge.append(bridge_length)
break
return count
on_bridge : 다리를 건너고 있는 트럭들의 각 무게
left_bridge : 다리를 건너고 있는 트럭이 완벽하게 건너기 위해 각 남은 길이
#한대씩만 or weigh 넘을 때 둘 다 break
while on_bridge or truck_weights:
count += 1
if len(on_bridge) == 0:
on_bridge.append(truck_weights.pop(0))
left_bridge.append(bridge_length)
일단 while문을 돌며 1초가 경과했기 때문에 left_bridge의 원소들를 각 -1씩 해준 뒤 가장 선두의 트럭이 다리를 다 건넜다면 left_bridge, on_bridge의 가장 앞 원소를 각각 pop 해준다.
for문을 돌면서 대기 트럭이 다리에 올라갈 수 있는지를 확인한다.
이 때 앞의 트럭이 올라가지 못한다면 뒤에 트럭들은 확인할 필요가 없으므로 break를 통해 for문을 빠져나간다.
else:
left_bridge = list(map(lambda x:x-1, left_bridge))
if left_bridge[0]==0:
left_bridge.pop(0)
on_bridge.pop(0)
for i in truck_weights:
if sum(on_bridge) + i <= weight:
on_bridge.append(truck_weights.pop(0))
left_bridge.append(bridge_length)
break