ps | |
---|---|
링크 | programmers.co.kr/… |
출처 | 프로그래머스 |
문제 번호 | 42583 |
문제명 | 다리를 지나는 트럭 |
레벨 | Level 2 |
분류 |
큐 |
시간복잡도 | O(n) |
인풋사이즈 | n<=10000 |
사용한 언어 | Python |
해결날짜 | 2021/05/21 |
태그 |
"""Solution code for "Programmers 42583. 다리를 지나는 트럭".
- Problem link: https://programmers.co.kr/learn/courses/30/lessons/42583
- Solution link: http://www.teferi.net/ps/problems/programmers/42583
"""
import collections
def solution(bridge_length, weight, truck_weights):
weight_sum = 0
trucks_on_bridge = collections.deque([0] * bridge_length)
sec = 0
for truck_weight in truck_weights:
while True:
sec += 1
weight_sum -= trucks_on_bridge.popleft()
if weight_sum + truck_weight <= weight:
trucks_on_bridge.append(truck_weight)
weight_sum += truck_weight
break
trucks_on_bridge.append(0)
return sec + bridge_length
"""Solution code for "Programmers 42583. 다리를 지나는 트럭".
- Problem link: https://programmers.co.kr/learn/courses/30/lessons/42583
- Solution link: http://www.teferi.net/ps/problems/programmers/42583
"""
import collections
Truck = collections.namedtuple('Truck', ['weight', 'enter_time'])
def solution(bridge_length, weight, truck_weights):
weight_sum = 0
trucks_on_bridge = collections.deque()
cur_sec = 0
for cur_truck_weight in truck_weights:
cur_sec += 1
if (trucks_on_bridge and
trucks_on_bridge[0].enter_time + bridge_length <= cur_sec):
weight_sum -= trucks_on_bridge.popleft().weight
while weight_sum + cur_truck_weight > weight:
out_truck = trucks_on_bridge.popleft()
cur_sec = out_truck.enter_time + bridge_length
weight_sum -= out_truck.weight
trucks_on_bridge.append(Truck(cur_truck_weight, cur_sec))
weight_sum += cur_truck_weight
return cur_sec + bridge_length