2021. 7. 28. 08:05ใ๐ฑ Algorithm
๋ ธ๋ ๊ฐ์ ์ต์ ๊ฑฐ๋ฆฌ๋ฅผ ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ์ผ๋ก ๊ตฌํ๋ ๋ฌธ์ ์ด๋ค.
1๋ฒ ๋ ธ๋๋ฅผ ๊ธฐ์ค์ผ๋ก ์ต์ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ๋๋ฐ, heap ํน์ deque ์ ์ฌ์ฉํ์ฌ ์ ๊ทผ ํ ์ ์๋ค.
๐ heap ์ ์ฌ์ฉํ ํ์ด
import heapq
def solution(N, road, K):
distance = [float('inf')] * (N + 1)
adj = [[] for _ in range(N + 1)]
for r in road:
adj[r[0]].append([r[2], r[1]])
adj[r[1]].append([r[2], r[0]])
distance[1] = 0
heap = []
heapq.heappush(heap, [0, 1])
while heap:
cost, node = heapq.heappop(heap)
for c, n in adj[node]:
if distance[n] > cost + c:
distance[n] = cost + c
heapq.heappush(heap, [distance[n], n])
return len([i for i in distance if i <= K])
์ ํ์ด๋ ์ต์ heap ์ ์ฌ์ฉํ๋ค.
10 ~ 11 ๋ผ์ธ์์, r[2] ๊ฐ ์ฒซ๋ฒ์งธ ์์๋ก append ๋๋๋ฐ, ์ด๋ r[2] ๊ฐ distance ๋ฅผ ์๋ฏธํ๊ธฐ ๋๋ฌธ์ด๋ค.
์ฐ๋ฆฌ๋ ์ต์ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ๋ ๋ฌธ์ ๋ฅผ ํ๊ณ ์๊ธฐ ๋๋ฌธ์, ๊ฑฐ๋ฆฌ์ ํด๋น๋๋ r[2] ๋ฅผ ์ต์ heap ์ ์ฒซ๋ฒ์งธ ์ธ์์ ๋ฃ๋ ๊ฒ์ด ์ณ๋ค.
๐ deque ์ ์ฌ์ฉํ ํ์ด
from collections import deque
def solution(N, road, K):
adjacent = dict()
distance = {i: float('inf') if i != 1 else 0 for i in range(1, N + 1)}
for n1, n2, d in road:
adjacent[n1] = adjacent.get(n1, []) + [(n2, d)]
adjacent[n2] = adjacent.get(n2, []) + [(n1, d)]
que = deque([1])
while que:
cur_node = que.popleft()
for n2, d in adjacent[cur_node]:
if distance[n2] > distance[cur_node] + d:
distance[n2] = distance[cur_node] + d
que.append(n2)
return len([i for i in distance.values() if i <= K])
deque ๊ณผ dictionary ๋ฅผ ์ฌ์ฉํ๋ค.
dictionary ์ get() ๋ฉ์๋๋ฅผ ์ ์ฉํ๊ฒ ์ฌ์ฉํ ์ ์๋๋ฐ, ์ฌ์ฉํ๊ณ ์ ํ๋ key๊ฐ dictionary์ ์กด์ฌํ์ง ์๋ ๊ฒฝ์ฐ์, get() ์ 2๋ฒ์งธ ์ธ์๋ฅผ value ๊ฐ์ผ๋ก ๋์ฒดํ๋ค.
๐ ์ํ์ฐฉ์ค
deque์ ์ฌ์ฉํ ํ์ด ๋ง์ง๋ง ๋ผ์ธ์์, distance ๋์ ๋๋ฆฌ๋ฅผ for ๋ฌธ์ผ๋ก ๋๋ฆด ๋, distance.values() ๊ฐ ์๋ distance ์์ฒด๋ฅผ ๋ฃ์๋ค. ๊ฑฐ๋ฆฌ๊ฐ(value) ์ด ์๋ ๋ ธ๋ (key) ๊ฐ์ด ๋ค์ด๊ฐ๊ธฐ ๋๋ฌธ์ ์๋ฑํ ๋ต์ด ๋์๋ค.
'๐ฑ Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
ํ๋ก๊ทธ๋๋จธ์ค [lv2] ๋ฉ๋ด ๋ฆฌ๋ด์ผ ํ์ด์ฌ (0) | 2021.08.29 |
---|---|
ํ๋ก๊ทธ๋๋จธ์ค [lv2] ๊ฑฐ๋ฆฌ๋๊ธฐ ํ์ธํ๊ธฐ ํ์ด์ฌ (0) | 2021.08.03 |
ํ๋ก๊ทธ๋๋จธ์ค [lv2] ํ์ผ๋ช ์ ๋ ฌ ํ์ด์ฌ (0) | 2021.07.25 |
ํ๋ก๊ทธ๋๋จธ์ค [lv1] ์ ๊ท์์ด๋์ถ์ฒ (0) | 2021.07.22 |
ํ๋ก๊ทธ๋๋จธ์ค [lv1] ์ซ์ ๋ฌธ์์ด๊ณผ ์๋จ์ด ํ์ด์ฌ (0) | 2021.07.21 |