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

์ž‘์„ฑ:    

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

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

ํƒœ๊ทธ: , , ,

๋ฌธ์ œ ์ถœ์ฒ˜

BAEKJOON Online Judge #11779


๋ฌธ์ œ

n(1โ‰คnโ‰ค1,000)๊ฐœ์˜ ๋„์‹œ๊ฐ€ ์žˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ํ•œ ๋„์‹œ์—์„œ ์ถœ๋ฐœํ•˜์—ฌ ๋‹ค๋ฅธ ๋„์‹œ์— ๋„์ฐฉํ•˜๋Š” m(1โ‰คmโ‰ค100,000)๊ฐœ์˜ ๋ฒ„์Šค๊ฐ€ ์žˆ๋‹ค. ์šฐ๋ฆฌ๋Š” A๋ฒˆ์งธ ๋„์‹œ์—์„œ B๋ฒˆ์งธ ๋„์‹œ๊นŒ์ง€ ๊ฐ€๋Š”๋ฐ ๋“œ๋Š” ๋ฒ„์Šค ๋น„์šฉ์„ ์ตœ์†Œํ™” ์‹œํ‚ค๋ ค๊ณ  ํ•œ๋‹ค. ๊ทธ๋Ÿฌ๋ฉด A๋ฒˆ์งธ ๋„์‹œ์—์„œ B๋ฒˆ์งธ ๋„์‹œ ๊นŒ์ง€ ๊ฐ€๋Š”๋ฐ ๋“œ๋Š” ์ตœ์†Œ๋น„์šฉ๊ณผ ๊ฒฝ๋กœ๋ฅผ ์ถœ๋ ฅํ•˜์—ฌ๋ผ.ย ํ•ญ์ƒ ์‹œ์ž‘์ ์—์„œ ๋„์ฐฉ์ ์œผ๋กœ์˜ ๊ฒฝ๋กœ๊ฐ€ ์กด์žฌํ•œ๋‹ค.


์ž…๋ ฅ

์ฒซ์งธ ์ค„์— ๋„์‹œ์˜ ๊ฐœ์ˆ˜ 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
3
1 3 5


My Sol

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

n = int(input())
m = int(input())
visit = [0]*(n+1)
G = [[] for _ in range(n+1)]
D = [[inf, []] for _ in range(n+1)]

while m > 0:
    s, e, w = map(int, input().split())
    m -= 1
    G[s].append((e, w))

S, E = map(int, input().split())
D[S][0] = 0
D[S][1] = [S]

Q = [(D[S][0], 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][0] > D[u][0]+w:
            D[v][0] = D[u][0]+w
            D[v][1] = D[u][1]+[v]
            heappush(Q, (D[v][0], v))

print(D[E][0])
print(len(D[E][1]))
print(*D[E][1])

๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ํ™œ์šฉํ•˜๋Š” ๋ฌธ์ œ์˜€๋‹ค. ๋‹ค๋งŒ ๊ฒฝ๋กœ๋ฅผ ๋ชจ๋‘ ํ‘œ์‹œํ•ด์•ผ ํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— D ๋ฐฐ์—ด์„ ๊ธฐ์กด ์ตœ์†Œ๋น„์šฉ๋งŒ ๊ธฐ๋กํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ, ์ตœ์†Œ๋น„์šฉ์„ ๊ธฐ๋กํ•จ๊ณผ ๋™์‹œ์— ์‹œ์ž‘์ ์œผ๋กœ๋ถ€ํ„ฐ์˜ ๊ฒฝ๋กœ๋ฅผ ์ €์žฅํ•˜๋Š” 1๋ฒˆ ์ธ๋ฑ์Šค ๋ฐฐ์—ด์„ ํ•˜๋‚˜์”ฉ ์œ„์น˜ํ•˜๊ฒŒ ํ•˜์—ฌ, ์ตœ์†Œ๋น„์šฉ์ด ๊ฐฑ์‹ ๋  ๋•Œ, ๊ธฐ์ค€์ ์˜ ๊ฒฝ๋กœ์— ํ˜„์žฌ ์ ์˜ ์ขŒํ‘œ๋ฅผ ๋”ํ•ด 1๋ฒˆ ์ธ๋ฑ์Šค์— ๊ฐฑ์‹ ์ €์žฅํ•˜๋„๋ก ํ•˜์˜€๋‹ค.


๊ฒฐ๊ณผ

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

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