본문 바로가기
CS/Algorithm

스택 > 다리를 지나는 트럭

by KJY 2021. 3. 28.

문제

코딩테스트 연습 - 다리를 지나는 트럭

풀이

import collections

class Bridge:
    def __init__(self, bridge_length, weight):
        self.possible_weight = weight
        self.cur_weight = 0
        truck_dummy = 0
        self.bridge_deque = collections.deque()
        for _ in range(bridge_length):
            self.bridge_deque.append(truck_dummy)

    def cross(self, truck_weight):
        self.cur_weight += truck_weight
        self.bridge_deque.append(truck_weight)
        crossed_weight = self.bridge_deque.popleft()
        self.cur_weight -= crossed_weight
        return crossed_weight

    def judge(self, truck_weight):
        if self.possible_weight + self.bridge_deque[0]  >= self.cur_weight + truck_weight:
            return True
        else:
            return False


def solution(bridge_length, weight, truck_weights):
    answer = 0
    bridge = Bridge(bridge_length, weight)
    total_weight = sum(truck_weights)
    crossed_weight = 0
    while(crossed_weight != total_weight):
        answer += 1
        if truck_weights:
            truck_weight = truck_weights[0]
        else:
            truck_weight = 0
        if bridge.judge(truck_weight):
            if truck_weights:
                crossed_weight += bridge.cross(truck_weights.pop(0))
            else:
                crossed_weight += bridge.cross(0)
        else:
            crossed_weight += bridge.cross(0)
    return answer

속도

  • min : 통과 (0.03ms, 10.3MB)
  • max : 통과 (189.64ms, 10.3MB)

다른 풀이

'CS > Algorithm' 카테고리의 다른 글

백준 9093  (0) 2021.05.17
백준 9012번  (0) 2021.05.17
해시 > 전화번호 목록  (0) 2021.04.04
힙 > 더 맵게  (0) 2021.04.04
해시> 완주하지 못한 선수  (0) 2021.03.28

댓글