๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/boj

BOJ 1916 - ์ตœ์†Œ๋น„์šฉ ๊ตฌํ•˜๊ธฐ

by HandHand 2021. 6. 7.

๋ฌธ์ œ

๋ฐฑ์ค€ ์˜จ๋ผ์ธ ์ €์ง€ - 1916๋ฒˆ

ํ’€์ด ๊ณผ์ •

ํ•œ ์ •์ ์œผ๋กœ๋ถ€ํ„ฐ ๋‹ค๋ฅธ ๋ชจ๋“  ์ •์ ๊นŒ์ง€์˜ ๊ฒฝ๋กœ ์ •๋ณด๋ฅผ ์‚ฌ์šฉํ•ด ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์ตœ์•…์˜ ๊ฒฝ์šฐ V = 1000์ด๊ณ  E = 100,000 ์ด๋ฏ€๋กœ O(ElgV) ์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ๊ฐ€์ง€๋Š” ๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์„ ์‚ฌ์šฉํ•ด์„œ ๋‹ต์„ ๊ตฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ


import sys
import heapq


N = int(input())
M = int(input())

adj = [[] for _ in range(1001)]
for _ in range(M):
    frm, to, cost = list(map(int, sys.stdin.readline().split()))
    adj[frm].append([to, cost])
start, goal = list(map(int, sys.stdin.readline().split()))


def dijkstra():
    pq = []
    dist = [sys.maxsize] * (N+1)

    dist[start] = 0
    heapq.heappush(pq, (0, start))

    while pq:
        here = heapq.heappop(pq)

        if dist[here[1]] < here[0]:
            continue

        for near in adj[here[1]]:
            next_dist = near[1] + here[0]

            if next_dist < dist[near[0]]:
                dist[near[0]] = next_dist
                heapq.heappush(pq, (next_dist, near[0]))

    return dist[goal]


def solution():
    answer = dijkstra()
    return answer


print(solution())
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > boj' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

BOJ 2252 - ์ค„ ์„ธ์šฐ๊ธฐ  (0) 2021.06.07
BOJ 2231 - ๋ถ„ํ•ดํ•ฉ  (0) 2021.06.07
BOJ 15684 - ์‚ฌ๋‹ค๋ฆฌ ์กฐ์ž‘  (0) 2021.06.07
BOJ 1781 - ์ปต๋ผ๋ฉด  (0) 2021.06.07
BOJ 6118 - ์ˆจ๋ฐ”๊ผญ์งˆ  (0) 2021.06.07

๐Ÿ’ฌ ๋Œ“๊ธ€