강의로 돌아가기
박건후

[스포주의] 파이썬 풀이 공유합니다

이 문제 설명이 참 애매했어서 헤맸는데,

  • 트럭에 순서가 정해져 있다는 점
  • 트럭이 1초마다 1만큼 움직인다는 점 을 알게 되면 잘 푸실 것이라 생각합니다.

풀이는 다음과 같습니다.
다리(queue)에 있는 트럭을 하나씩 빼고,
다리의 하중 여유가 된다면 트럭을 추가하는 방식으로 했습니다,
만약 다리의 하중 여유가 되지 않는다면(total + orders[0] > weight), 무게가 0짜리인 트럭을 넣어줬고요(append).
만약 다리의 하중 여유가 된다면, total에는 w를 더해주고, 다리(queue)에는 w를 넣어줬습니다(append).

from collections import deque

def solution(bridge_length, weight, truck_weights):
    queue = deque([0]*bridge_length)
    orders = deque(truck_weights)
    time=0
    total=0
    while orders:
        time+=1
        total -= queue[0]
        queue.popleft()
        if total + orders[0] > weight:
            queue.append(0)
        else:
            w = orders.popleft()
            total+=w
            queue.append(w)

    return time+bridge_length
작성중인 코드―solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from collections import deque

def solution(bridge_length, weight, truck_weights):
    queue = deque([0]*bridge_length)
    orders = deque(truck_weights)
    time=0
    total=0
    while orders:
        time+=1
        total -= queue[0]
        queue.popleft()
        if total + orders[0] > weight:
            queue.append(0)
        else:
            w = orders.popleft()
            total+=w
            queue.append(w)

    return time+bridge_length
  • 김태경

    너무 깔끔해서 감명받았습니다.

    김태경―Feb 28, 2023 19:27
0 개의 답변
답변 쓰기
This input form supports markdown syntax. Please refer to 마크다운 가이드.