[๋ฐฑ์ค€/python] 1753๋ฒˆ : ์ตœ๋‹จ๊ฒฝ๋กœ

2021. 9. 1. 23:58

๋ฌธ์ œ

๋ฐฉํ–ฅ๊ทธ๋ž˜ํ”„๊ฐ€ ์ฃผ์–ด์ง€๋ฉด ์ฃผ์–ด์ง„ ์‹œ์ž‘์ ์—์„œ ๋‹ค๋ฅธ ๋ชจ๋“  ์ •์ ์œผ๋กœ์˜ ์ตœ๋‹จ ๊ฒฝ๋กœ๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. ๋‹จ, ๋ชจ๋“  ๊ฐ„์„ ์˜ ๊ฐ€์ค‘์น˜๋Š” 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๋ฅผ ์ถœ๋ ฅํ•˜๋ฉด ๋œ๋‹ค.

 

์ •๋‹ต

import heapq
import sys
input = sys.stdin.readline

V, E = map(int, input().split())
K = int(input())

INF = int(1e9)
point = [INF]*(V+1)
graph = {n:[] for n in range(1, V+1)}    # ์‹œ์ž‘ ๋…ธ๋“œ : [(๋„์ฐฉ ๋…ธ๋“œ, ๊ฐ€์ค‘์น˜)]
for _ in range(E):
    u, v, w = map(int, input().split())
    graph[u].append((v,w))

def dijkstra(n):
    queue = []
    heapq.heappush(queue, (0, n))
    point[n] = 0

    while queue:
        start, end = heapq.heappop(queue)
        if point[end] < start:
            continue

        for node in graph[end]:
            cost = start + node[1]

            if cost < point[node[0]]:
                point[node[0]] = cost
                heapq.heappush(queue, (cost, node[0]))

dijkstra(K)
for p in point[1:]:
    if p == INF:
        print("INF")
    else:
        print(p)
728x90

BELATED ARTICLES

more