[๋ฐฑ์ค€] ์ตœ๋‹จ๊ฒฝ๋กœ / 1753๋ฒˆ / ํŒŒ์ด์ฌ / Python / Dijkstra
Algorithm/Baekjoon

[๋ฐฑ์ค€] ์ตœ๋‹จ๊ฒฝ๋กœ / 1753๋ฒˆ / ํŒŒ์ด์ฌ / Python / Dijkstra

728x90
๋ฐ˜์‘ํ˜•

 

๐Ÿ’กsolutions )

๐Ÿ’ฌ ์ด๋ฒˆ ๋ฌธ์ œ๋Š” ์ตœ๋‹จ ๊ฒฝ๋กœ๋ฅผ ํ’€ ๋•Œ ๊ฐ€์žฅ ๋Œ€ํ‘œ์ ์ธ ๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ํ†ตํ•ด ํ•ด๊ฒฐํ–ˆ๋‹ค.

๐Ÿ’ฌ heap ์ž๋ฃŒ๊ตฌ์กฐ ์‚ฌ์šฉํ•˜์—ฌ heappop()์„ ํ–ˆ์„ ๋•Œ ๊ฐ€์žฅ ์ตœ๋‹จ ๊ฒฝ๋กœ๊ฐ€ ๋‚˜์˜ค๊ฒŒ ํ•œ๋‹ค.

 

๐ŸŽซcode )

import heapq
import sys

input = sys.stdin.readline


def dijkstra(v, s, adj):
    dist = [INF] * (v + 1)  # ์ตœ๋‹จ๊ฒฝ๋กœ ๋ฆฌ์ŠคํŠธ
    dist[s] = 0
    heap = []
    heapq.heappush(heap, [0, s])

    while heap:
        cost, node = heapq.heappop(heap)  # ์ตœ์†Œํž™ ์ด์šฉ
        for n, c in adj[node]:
            c += cost
            if c < dist[n]:
                dist[n] = c
                heapq.heappush(heap, [c, n])
    return dist


V, E = map(int, input().split())
s = int(input())
adj = [[] for _ in range(V + 1)]
INF = float('inf')  # ์ดˆ๊ธฐ๊ฐ’์€ ๋ฌดํ•œ๋Œ€
for i in range(E):  # ์ธ์ ‘๋ฆฌ์ŠคํŠธ
    u, v, w = map(int, input().split())
    adj[u].append([v, w])

for res in dijkstra(V, s, adj)[1:]:
    print(res if res != INF else 'INF')

 

๐Ÿ“Œ description )

๋ฌธ์ œ์ถœ์ฒ˜ : www.acmicpc.net/problem/1753

 

1753๋ฒˆ: ์ตœ๋‹จ๊ฒฝ๋กœ

์ฒซ์งธ ์ค„์— ์ •์ ์˜ ๊ฐœ์ˆ˜ V์™€ ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ E๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (1≤V≤20,000, 1≤E≤300,000) ๋ชจ๋“  ์ •์ ์—๋Š” 1๋ถ€ํ„ฐ V๊นŒ์ง€ ๋ฒˆํ˜ธ๊ฐ€ ๋งค๊ฒจ์ ธ ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•œ๋‹ค. ๋‘˜์งธ ์ค„์—๋Š” ์‹œ์ž‘ ์ •์ ์˜ ๋ฒˆํ˜ธ K(1≤K≤V)๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.

www.acmicpc.net

๋ฌธ์ œ

๋ฐฉํ–ฅ๊ทธ๋ž˜ํ”„๊ฐ€ ์ฃผ์–ด์ง€๋ฉด ์ฃผ์–ด์ง„ ์‹œ์ž‘์ ์—์„œ ๋‹ค๋ฅธ ๋ชจ๋“  ์ •์ ์œผ๋กœ์˜ ์ตœ๋‹จ ๊ฒฝ๋กœ๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. ๋‹จ, ๋ชจ๋“  ๊ฐ„์„ ์˜ ๊ฐ€์ค‘์น˜๋Š” 10 ์ดํ•˜์˜ ์ž์—ฐ์ˆ˜์ด๋‹ค.

์ž…๋ ฅ

์ฒซ์งธ ์ค„์— ์ •์ ์˜ ๊ฐœ์ˆ˜ V์™€ ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ E๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (1≤V≤20,000, 1≤E≤300,000) ๋ชจ๋“  ์ •์ ์—๋Š” 1๋ถ€ํ„ฐ V๊นŒ์ง€ ๋ฒˆํ˜ธ๊ฐ€ ๋งค๊ฒจ์ ธ ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•œ๋‹ค. ๋‘˜์งธ ์ค„์—๋Š” ์‹œ์ž‘ ์ •์ ์˜ ๋ฒˆํ˜ธ K(1≤K≤V)๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์…‹์งธ ์ค„๋ถ€ํ„ฐ E๊ฐœ์˜ ์ค„์— ๊ฑธ์ณ ๊ฐ ๊ฐ„์„ ์„ ๋‚˜ํƒ€๋‚ด๋Š” ์„ธ ๊ฐœ์˜ ์ •์ˆ˜ (u, v, w)๊ฐ€ ์ˆœ์„œ๋Œ€๋กœ ์ฃผ์–ด์ง„๋‹ค. ์ด๋Š” u์—์„œ v๋กœ ๊ฐ€๋Š” ๊ฐ€์ค‘์น˜ w์ธ ๊ฐ„์„ ์ด ์กด์žฌํ•œ๋‹ค๋Š” ๋œป์ด๋‹ค. u์™€ v๋Š” ์„œ๋กœ ๋‹ค๋ฅด๋ฉฐ w๋Š” 10 ์ดํ•˜์˜ ์ž์—ฐ์ˆ˜์ด๋‹ค. ์„œ๋กœ ๋‹ค๋ฅธ ๋‘ ์ •์  ์‚ฌ์ด์— ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๊ฐ„์„ ์ด ์กด์žฌํ•  ์ˆ˜๋„ ์žˆ์Œ์— ์œ ์˜ํ•œ๋‹ค.

์ถœ๋ ฅ

์ฒซ์งธ ์ค„๋ถ€ํ„ฐ V๊ฐœ์˜ ์ค„์— ๊ฑธ์ณ, i๋ฒˆ์งธ ์ค„์— i๋ฒˆ ์ •์ ์œผ๋กœ์˜ ์ตœ๋‹จ ๊ฒฝ๋กœ์˜ ๊ฒฝ๋กœ๊ฐ’์„ ์ถœ๋ ฅํ•œ๋‹ค. ์‹œ์ž‘์  ์ž์‹ ์€ 0์œผ๋กœ ์ถœ๋ ฅํ•˜๊ณ , ๊ฒฝ๋กœ๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ์—๋Š” INF๋ฅผ ์ถœ๋ ฅํ•˜๋ฉด ๋œ๋‹ค.

 

๋ฐ˜์‘ํ˜•