[BOJ][๐ŸŸก5][๋ฐฑ์ค€#01753] ์ตœ๋‹จ๊ฒฝ๋กœ

์ž‘์„ฑ:    

์—…๋ฐ์ดํŠธ:

์นดํ…Œ๊ณ ๋ฆฌ:

ํƒœ๊ทธ: , , ,

๋ฌธ์ œ ์ถœ์ฒ˜

BAEKJOON Online Judge #1753


๋ฌธ์ œ

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


์˜ˆ์ œ

์ž…๋ ฅ

5 6
1
5 1 1
1 2 2
1 3 3
2 3 4
2 4 5
3 4 6


์ถœ๋ ฅ

0
2
3
7
INF


My Sol

import sys
input = sys.stdin.readline
from heapq import heappop, heappush

def dijk(S):
    global D
    Q = [(D[S], S)]
    visit = [0]*(V+1)

    while Q:
        d, u = heappop(Q)
        if visit[u]: continue
        visit[u] = 1

        for v, w in G[u]:
            if not visit[v] and D[v] > D[u]+w:
                D[v] = D[u]+w
                heappush(Q, [D[v], v])


V, E = map(int, input().split())
S = int(input())-1
G = [[] for _ in range(V)]
D =  [0xffffff]*V
D[S] = 0
for _ in range(E):
    u, v, w = map(int, input().split())
    G[u-1].append((v-1, w))

dijk(S)
for val in D:
    print('INF' if val == 0xffffff else val)

๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ด์šฉํ•ด ํ‘ธ๋Š” ๋ฌธ์ œ์˜€๋‹ค. ์‹œ์ž‘์ ์„ ํ•จ์ˆ˜ ์ธ์ž๋กœ ๋ฐ›์•„ ์‹œ์ž‘ํ•œ๋‹ค. ์‹œ์ž‘์ ์œผ๋กœ๋ถ€ํ„ฐ์˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ๋ชจ๋‘ ๊ณ„์‚ฐํ•˜์—ฌ D์— ๋„ฃ์œผ๋ฉด, D๋ฅผ ์ฐจ๋ก€๋Œ€๋กœ ์ถœ๋ ฅํ•˜๋ฉด ๋˜๋Š”๋ฐ, ์ด๋•Œ ์ดˆ๊ธฐํ™”ํ–ˆ๋˜ ๊ฐ’์ด๋ผ๋ฉด INF๋ฅผ ์ถœ๋ ฅํ•˜๋ฉด ๋˜๊ฒ ๋‹ค.


๊ฒฐ๊ณผ

๋งž์•˜์Šต๋‹ˆ๋‹ค!!

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ