알고리즘 문제풀이/프로그래머스

[프로그래머스/Python/스택큐] Level 2 42583 - 다리를 지나는 트럭

sdbeans 2023. 7. 15. 15:10

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

[프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr](https://school.programmers.co.kr/learn/courses/30/lessons/42583)

Approach:

  1. Pop the first element of truck_weights as curr_truck
  2. Check the weight of current bridge.
    2-1. If current weight + curr_truck is less than or equal to the weight limit weight, append to the right of deque bridge, which keep track of the trucks currently on the bridge.
    2-2. If greater than weight, pop the first element of bridge and add weight - len(bridge) to the answer. Put curr_truck back to truck_weights.
  3. Repeat until truck_weights is empty. The number of leftover trucks on bridge are added to answer.
  4. Return answer

중간에 아이디어 수정하면서 코드 완성!

from collections import deque

def solution(bridge_length, weight, truck_weights):
    answer = 0
    truck_weights = deque(truck_weights)
    bridge = deque([0 for _ in range(bridge_length)])
    sum_bridge = 0
    while True:
        if len(truck_weights) == 0:
            answer += bridge_length
            break
        curr_truck = truck_weights.popleft()
        if sum_bridge - bridge[0] + curr_truck <= weight:
            bridge.append(curr_truck)
            sum_bridge += curr_truck
            off_bridge_truck = bridge.popleft()
            sum_bridge -= off_bridge_truck
            answer += 1
        else:
            truck_weights.appendleft(curr_truck)
            off_bridge_truck = bridge.popleft()
            sum_bridge -= off_bridge_truck
            bridge.append(0)
            answer += 1

    return answer