Algorithm/프로그래머스

[프로그래머스] 다리를 지나는 트럭 - 파이썬

potato_pizza 2024. 6. 25. 17:36
728x90

다리를 지나는 트럭

https://school.programmers.co.kr/learn/courses/30/lessons/42583?language=python3

 

프로그래머스

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

programmers.co.kr

 

문제

풀이

  • 큐를 활용한 풀이
  • 'time': 시뮬레이션 전체를 통틀어 경과한 시간을 추적
  • 'bridge': 다리를 현재 건너고 있는 트럭의 위치와 무게를 나타내는 큐, 길이는 'bridge_length'이며, 초기에는 0으로 채워져있음.
  • 'current_weights': 다리 위에 현존하는 트럭들의 총 무게
  • 'truck_weights': 대기 중인 트럭들의 무게 목록을 나타내는 큐
  • time을 +1씩 하면서 'bridge'에서 가장 앞에 있는 트럭을 제거하면서 'current_weights'에서 그 트럭 무게를 popleft()
  • 다리에 다음 트럭이 들어올 수 있는지 'current_weights + truck_weights[0] <= weight' 확인, 들어올 수 있으면 'bridge'와 'current_weights'에 추가하고, 대기열에서 제거하고, 들어올 수 없으면 'bridge'에 0을 추가하고 한 칸을 비워둠
  • 마지막 트럭이 다리에 올라간 후, 다리를 완전히 건너는데 필요한 시간을 더해주면 끝.
from collections import deque

def solution(bridge_length, weight, truck_weights):
    time = 0
    bridge = deque([0] * bridge_length)
    truck_weights = deque(truck_weights)

    current_weights = 0
    while len(truck_weights) != 0:
        time += 1
        current_weights -= bridge.popleft()

        if current_weights + truck_weights[0] <= weight:
            current_weights += truck_weights[0]
            bridge.append(truck_weights[0])
            truck_weights.popleft()
            # bridge.append(truck_weights.popleft())
        else:
            bridge.append(0)

    print(time)
    time += bridge_length

    return time
728x90
반응형