목차

다리를 지나는 트럭

ps
링크programmers.co.kr/…
출처프로그래머스
문제 번호42583
문제명다리를 지나는 트럭
레벨Level 2
분류

시간복잡도O(n)
인풋사이즈n<=10000
사용한 언어Python
해결날짜2021/05/21
태그

고득점 Kit - 스택/큐

풀이

코드

코드 1 - O(n*m)

"""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

코드 2 - O(n)

"""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