๋ฌธ์ œ๋ณด๋Ÿฌ๊ฐ€๊ธฐ

๐Ÿ•ต๏ธ‍โ™€๏ธ ๋ฌธ์ œ


 

 

 

๐Ÿ™‹‍โ™€๏ธ ํ’€์–ด๋ณด์ž~


1. ๋‹ค๋ฆฌ ์œ„์— ์žˆ๋Š” ํŠธ๋Ÿญ๋“ค์˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋”ฐ๋กœ ๋งŒ๋“ค์ž.

trucks_on_bridge -> ์—ฌ๊ธฐ์„œ len๋Š” bridge_length๋กœ ์ค€๋‹ค. ๊ทธ ๊ธธ์ด๋งŒํผ๋งŒ ํŠธ๋Ÿญ์ˆ˜๊ฐ€ ๋“ค์–ด๊ฐˆ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ

 

2. ์ด์ œ ๋‹ค๋ฆฌ์— ์˜ฌ๋ผ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ์ฐจ ๋Œ€์ˆ˜๋งŒํผ while๋ฌธ์„ ๋นŒ๋ฆฌ๋ฉด์„œ ์ง„ํ–‰ํ•œ๋‹ค.

๋‹ค๋ฆฌ์— ์˜ฌ๋ผ์™€ ์žˆ๋Š” ํŠธ๋Ÿญ์ด ์žˆ์œผ๋ฉด ๋งจ ์•ž์— ์žˆ๋Š” ํŠธ๋Ÿญ์„ ๋นผ์ฃผ๊ณ 

ํ˜„์žฌ ๋‹ค๋ฆฌ์— ์žˆ๋Š” ํŠธ๋Ÿญ๋“ค์˜ ํ•ฉ๊ณผ ์ƒˆ๋กœ ํˆฌ์ž…๋˜๊ธฐ๋ฅผ ๊ธฐ๋‹ค๋ฆฌ๋Š” truck_weights[0]์„ ํ•ฉํ–ˆ์„ ๋•Œ ๊ฒฌ๋”œ ์ˆ˜ ์žˆ๋Š”์ง€ ์ฒดํฌํ•œ๋‹ค.

๋œ๋‹ค๋ฉด ๋‹ค๋ฆฌ์— ์˜ฌ๋ ค์ฃผ๊ณ  ๋Œ€๊ธฐ ๋ชฉ๋ก์—์„œ ๋นผ์ค€๋‹ค.

์•ˆ๋œ๋‹ค๋ฉด ๊ทธ๋ƒฅ 0์„ ๋„ฃ์–ด์„œ ์˜ฌ๋ฆฌ์ง€ ๋ชปํ–ˆ์Œ์„ ๋ช…์‹œํ•œ๋‹ค.

 

 

 

 

def solution(bridge_length, weight, truck_weights):
    answer = 0
    trucks_on_bridge = [0] * bridge_length
    while len(trucks_on_bridge):
        answer += 1
        trucks_on_bridge.pop(0)
        if truck_weights:
            if sum(trucks_on_bridge) + truck_weights[0] <= weight:
                trucks_on_bridge.append(truck_weights.pop(0))
            else:
                trucks_on_bridge.append(0)
    return answer

 

 

<์ฐธ๊ณ ํ• ๋งŒํ•œ ๋‹ต์•ˆ>

import collections

DUMMY_TRUCK = 0


class Bridge(object):

    def __init__(self, length, weight):
        self._max_length = length
        self._max_weight = weight
        self._queue = collections.deque()
        self._current_weight = 0

    def push(self, truck):
        next_weight = self._current_weight + truck
        if next_weight <= self._max_weight and len(self._queue) < self._max_length:
            self._queue.append(truck)
            self._current_weight = next_weight
            return True
        else:
            return False

    def pop(self):
        item = self._queue.popleft()
        self._current_weight -= item
        return item

    def __len__(self):
        return len(self._queue)

    def __repr__(self):
        return 'Bridge({}/{} : [{}])'.format(self._current_weight, self._max_weight, list(self._queue))


def solution(bridge_length, weight, truck_weights):
    bridge = Bridge(bridge_length, weight)
    trucks = collections.deque(w for w in truck_weights)

    for _ in range(bridge_length):
        bridge.push(DUMMY_TRUCK)

    count = 0
    while trucks:
        bridge.pop()

        if bridge.push(trucks[0]):
            trucks.popleft()
        else:
            bridge.push(DUMMY_TRUCK)

        count += 1

    while bridge:
        bridge.pop()
        count += 1

    return count


def main():
    print(solution(2, 10, [7, 4, 5, 6]), 8)
    print(solution(100, 100, [10]), 101)
    print(solution(100, 100, [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]), 110)


if __name__ == '__main__':
    main()

+ Recent posts