DevYoon

[๋ฐฑ์ค€] 1504. ํŠน์ •ํ•œ ์ตœ๋‹จ ๊ฒฝ๋กœ (Python) ๋ณธ๋ฌธ

PS/Baekjoon

[๋ฐฑ์ค€] 1504. ํŠน์ •ํ•œ ์ตœ๋‹จ ๊ฒฝ๋กœ (Python)

gimewn 2022. 6. 3. 13:35

link ๐Ÿ”— https://www.acmicpc.net/problem/1504

 

1504๋ฒˆ: ํŠน์ •ํ•œ ์ตœ๋‹จ ๊ฒฝ๋กœ

์ฒซ์งธ ์ค„์— ์ •์ ์˜ ๊ฐœ์ˆ˜ N๊ณผ ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ E๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (2 ≤ N ≤ 800, 0 ≤ E ≤ 200,000) ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ E๊ฐœ์˜ ์ค„์— ๊ฑธ์ณ์„œ ์„ธ ๊ฐœ์˜ ์ •์ˆ˜ a, b, c๊ฐ€ ์ฃผ์–ด์ง€๋Š”๋ฐ, a๋ฒˆ ์ •์ ์—์„œ b๋ฒˆ ์ •์ ๊นŒ์ง€ ์–‘๋ฐฉํ–ฅ ๊ธธ์ด ์กด

www.acmicpc.net

 

๐Ÿ”ฅ ์ฃผ์–ด์ง„ ๋‘ ์ •์ ์„ ๋ฐ˜๋“œ์‹œ ํ†ต๊ณผํ•ด์•ผ ํ•˜๋ฏ€๋กœ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋‘ ๊ฒฝ์šฐ๋กœ ๋‚˜๋ˆ„์–ด ๊ณ„์‚ฐํ•˜์˜€๋‹ค.

๐Ÿ”ฅ ์‹œ์ž‘์  โžก๏ธ ์ •์  1 โžก๏ธ ์ •์  2 โžก๏ธ ๋์ 

๐Ÿ”ฅ ์‹œ์ž‘์  โžก๏ธ ์ •์  2 โžก๏ธ ์ •์  1 โžก๏ธ ๋์ 

๐Ÿ”ฅ ๋‘ ๊ฒฝ์šฐ ์ค‘ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์ด ์ •๋‹ต!

 

import heapq
import sys

N, E = map(int, sys.stdin.readline().split())

board = [[] for _ in range(N+1)]

for _ in range(E):
    a, b, c = map(int, sys.stdin.readline().split())
    board[a].append((b, c))
    board[b].append((a, c))

m1, m2 = map(int, sys.stdin.readline().split())

def dijkstra(start):
    heap = []
    heapq.heappush(heap, (0, start)) # ๋น„์šฉ, ๊ฒฝ์œ ์ง€
    result = [2e18] * (N + 1)
    result[start] = 0
    while heap:
        cost, now = heapq.heappop(heap)
        if cost > result[now]:
            continue
        for b in board[now]:
            newcost = cost+b[1]
            if newcost < result[b[0]]:
                result[b[0]] = newcost
                heapq.heappush(heap, (newcost, b[0]))
    return result

# 1 -> m1 -> m2 -> N
# 1 -> m2 -> m1 -> N

res_one = dijkstra(1)
res_m1 = dijkstra(m1)
res_m2 = dijkstra(m2)

ans = min(res_one[m1]+res_m1[m2]+res_m2[N], res_one[m2]+res_m2[m1]+res_m1[N])

if ans < 2e18:
    print(ans)
else:
    print(-1)