๋ฌธ์ ๋ณด๋ฌ๊ฐ๊ธฐ
๐ต๏ธโ๏ธ ๋ฌธ์
๐โ๏ธ ํ์ด๋ณด์~
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()
'๐ต๏ธโโ๏ธ > programmers' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Python] programmers - ๋คํธ์ํฌ (BFS/DFS) (0) | 2021.11.17 |
---|---|
[Python] programmers - ๊ธฐ๋ฅ๊ฐ๋ฐ ( ์คํ/ํ ) (0) | 2021.11.04 |