[BOJ][๐ŸŸก5][๋ฐฑ์ค€#01916] ์ตœ์†Œ๋น„์šฉ ๊ตฌํ•˜๊ธฐ

์ž‘์„ฑ:    

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

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

ํƒœ๊ทธ: , , ,

๋ฌธ์ œ ์ถœ์ฒ˜

BAEKJOON Online Judge #1916


๋ฌธ์ œ

N๊ฐœ์˜ย ๋„์‹œ๊ฐ€ ์žˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ํ•œ ๋„์‹œ์—์„œ ์ถœ๋ฐœํ•˜์—ฌ ๋‹ค๋ฅธ ๋„์‹œ์— ๋„์ฐฉํ•˜๋Š” M๊ฐœ์˜ ๋ฒ„์Šค๊ฐ€ ์žˆ๋‹ค. ์šฐ๋ฆฌ๋Š” A๋ฒˆ์งธ ๋„์‹œ์—์„œ B๋ฒˆ์งธ ๋„์‹œ๊นŒ์ง€ ๊ฐ€๋Š”๋ฐ ๋“œ๋Š” ๋ฒ„์Šค ๋น„์šฉ์„ ์ตœ์†Œํ™” ์‹œํ‚ค๋ ค๊ณ  ํ•œ๋‹ค.ย A๋ฒˆ์งธ ๋„์‹œ์—์„œ B๋ฒˆ์งธ ๋„์‹œ๊นŒ์ง€ ๊ฐ€๋Š”๋ฐ ๋“œ๋Š” ์ตœ์†Œ๋น„์šฉ์„ ์ถœ๋ ฅํ•˜์—ฌ๋ผ. ๋„์‹œ์˜ ๋ฒˆํ˜ธ๋Š” 1๋ถ€ํ„ฐ N๊นŒ์ง€์ด๋‹ค.


์ž…๋ ฅ

์ฒซ์งธ ์ค„์— ๋„์‹œ์˜ ๊ฐœ์ˆ˜ N(1 โ‰ค N โ‰ค 1,000)์ด ์ฃผ์–ด์ง€๊ณ  ๋‘˜์งธ ์ค„์—๋Š” ๋ฒ„์Šค์˜ ๊ฐœ์ˆ˜ M(1 โ‰ค M โ‰ค 100,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์…‹์งธ ์ค„๋ถ€ํ„ฐ M+2์ค„๊นŒ์ง€ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ฒ„์Šค์˜ ์ •๋ณด๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋จผ์ € ์ฒ˜์Œ์—๋Š” ๊ทธ ๋ฒ„์Šค์˜ ์ถœ๋ฐœ ๋„์‹œ์˜ ๋ฒˆํ˜ธ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๊ทธ ๋‹ค์Œ์—๋Š” ๋„์ฐฉ์ง€์˜ ๋„์‹œ ๋ฒˆํ˜ธ๊ฐ€ ์ฃผ์–ด์ง€๊ณ  ๋˜ ๊ทธ ๋ฒ„์Šค ๋น„์šฉ์ด ์ฃผ์–ด์ง„๋‹ค. ๋ฒ„์Šค ๋น„์šฉ์€ 0๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , 100,000๋ณด๋‹ค ์ž‘์€ ์ •์ˆ˜์ด๋‹ค. ๊ทธ๋ฆฌ๊ณ  M+3์งธ ์ค„์—๋Š” ์šฐ๋ฆฌ๊ฐ€ ๊ตฌํ•˜๊ณ ์ž ํ•˜๋Š” ๊ตฌ๊ฐ„ ์ถœ๋ฐœ์ ์˜ ๋„์‹œ๋ฒˆํ˜ธ์™€ ๋„์ฐฉ์ ์˜ ๋„์‹œ๋ฒˆํ˜ธ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ถœ๋ฐœ์ ์—์„œ ๋„์ฐฉ์ ์„ ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ๋งŒ ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง„๋‹ค.


์ถœ๋ ฅ

์ฒซ์งธ ์ค„์— ์ถœ๋ฐœ ๋„์‹œ์—์„œ ๋„์ฐฉ ๋„์‹œ๊นŒ์ง€ ๊ฐ€๋Š”๋ฐ ๋“œ๋Š” ์ตœ์†Œ ๋น„์šฉ์„ ์ถœ๋ ฅํ•œ๋‹ค.


์˜ˆ์ œ

์ž…๋ ฅ

5
8
1 2 2
1 3 3
1 4 1
1 5 10
2 4 2
3 4 1
3 5 1
4 5 3
1 5


์ถœ๋ ฅ

4


My Sol

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

N = int(input())
M = int(input())
D = [0xffffff]*N
visit = [0]*N
G = [[] for _ in range(N)]
for _ in range(M):
    s, e, w = map(int, input().split())
    s, e = s-1, e-1
    G[s].append((e, w))

S, E = map(int, input().split())
S, E = S-1, E-1
D[S] = 0
Q = [(D[S], S)]
while Q:
    val, 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))

print(D[E])

์šฐ์„ ์ˆœ์œ„ ํ์ธ heap๊ณผ ๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•˜๋Š” ์ „ํ˜•์ ์ธ ๋ฌธ์ œ์˜€๋‹ค. ํ…œํ”Œ๋ฆฟ์„ ์ •์„๋Œ€๋กœ ์‚ฌ์šฉํ•˜๋ฉด ๋˜๋Š” ๋ถ€๋ถ„์ด์—ˆ๊ธฐ ๋•Œ๋ฌธ์— ๊ทธ๋ฆฌ ์–ด๋ ต์ง„ ์•Š์•˜๋‹ค. ๋‹ค๋งŒ visit ์ฒดํฌ๋ฅผ ์ธ์ ‘์ •์  v์—์„œ ํ•ด์ฃผ๋Š” ์ค„ ์•Œ์•˜๋Š”๋ฐ, Q์—์„œ ๋นผ๋‚ธ ๊ธฐ์ค€ ์ •์  ์ž์ฒด๋ฅผ visit ์ฒดํฌํ•˜๋Š” ์ ์ด ๋‚ด๊ฐ€ ์ž˜ ์ˆ™์ง€๋ฅผ ๋ชปํ•˜๊ณ  ์žˆ์—ˆ์Œ์„ ์•Œ๊ฒŒ ๋˜์—ˆ๋‹ค.


๊ฒฐ๊ณผ

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

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