algorithm/python

프로그래머스/스택,큐/다리를 지나는 트럭

아르르르를를르 2022. 6. 21. 17:11

https://programmers.co.kr/learn/courses/30/lessons/42583

문제 조건 +)

문제에 빠져있는 조건이 있어 계속 틀렸다. "트럭은 1초 다리 1칸씩 전진한다"는 조건을 추가해야 한다.

 

from collections import deque

def solution(bridge_length, weight, truck_weights):
    answer = 0
    truck_weights = deque(truck_weights)
    inBridge = deque([0]*bridge_length)
    
    weight_sum = 0
    while truck_weights or sum(inBridge) > 0:
        answer += 1
        getOut = inBridge.popleft()
        weight_sum -= getOut
        
        if truck_weights and weight_sum + truck_weights[0] <= weight:
            getIn = truck_weights.popleft()
            weight_sum += getIn
            inBridge.append(getIn)
        else:
            inBridge.append(0)
    return answer

if __name__ == "__main__":
    assert solution(2, 10, [7, 4, 5, 6]) == 8