|
์ฝ๋ ์์ฑํ๊ธฐ
import heapq, sys
def solution(N, road, K):
distance=[sys.maxsize]*(N+1)
graph=[[] for _ in range(N+1)]
for r in road :
graph[r[0]].append([r[1], r[2]])
graph[r[1]].append([r[0], r[2]])
def dijkstra(start) :
distance[start]=0
q=[]
heapq.heappush(q, [0, start])
while q :
weight, node=heapq.heappop(q)
for next_node, wei in graph[node]:
if wei+weight<distance[next_node]:
distance[next_node]=wei+weight
heapq.heappush(q, [wei+weight, next_node])
dijkstra(1)
return len([x for x in distance if x<=K])
Python
๋ณต์ฌ
|
์ฝ๋ ์ค๋ช
ํ๊ธฐ
๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ์ ์ด์ฉํด์ ์ ์ 1์์ ์์ํด์ ๋ชจ๋ ์ ์ ์ผ๋ก ๊ฐ๋ ์ต๋จ ๊ฒฝ๋ก๋ฅผ ๊ตฌํ๋ ๋ฐฉ๋ฒ์ ์ด์ฉํ๋ค.
๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ์ heapq๋ฅผ ์ด์ฉํด ํ์๋ค.
1.
๊ฒฝ๋ก๋ฅผ ๊ทธ๋ํ์ ์ ์ฅ์ ํ๋ค.
2.
์์ ์ ์ -์์์ ์ ๊ฑฐ๋ฆฌ๋ฅผ 0์ผ๋ก ํ๊ณ heapq์ [๋น์ฉ, ์ ์ ]์ ์ฝ์
ํ๋ค.
a.
heapq์ ์ฝ์
ํ ๋๋ [๋น์ฉ, ์ ์ ] ์์ผ๋ก ๋ฃ์ด์ผ ๋น์ฉ ๊ธฐ์ค์ผ๋ก ์ต๋จ ๊ฒฝ๋ก๋ฅผ ๊ตฌํ ์ ์๋ค.
3.
heapq๊ฐ ๋น ๋๊น์ง ๋ฐ๋ณต์ ํ๋ค.
a.
queue์์ ์ฐ์ ์์๊ฐ ๋์ ์์๋ฅผ popํ๋ค.
b.
ํด๋น node์ ์ฐ๊ฒฐ๋ ์ ์ ์ ํ๋์ฉ ๋๋ฌ๋ณธ๋ค.
c.
๊ฐ์ค์น๋ฅผ ๋น๊ตํด์ ์ต๋จ ๊ฒฝ๋ก์ด๊ธฐ ๋๋ฌธ์ ๊ฐ์ค์น๊ฐ ์๋ค๋ฉด ์ฐ๊ฒฐ๋ ์ ์ ๊น์ง์ ๊ฑฐ๋ฆฌ๋ฅผ updateํ๊ณ heapq์ ์ฝ์
ํ๋ค.
4.
๋ฐฐ๋ฌํ ์๊ฐ์ด K๋ณด๋ค ์์ ์์๋ค์ ๊ฐ์๋ฅผ ๋ฐํํ๋ค.