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

BOJ 5972 - ํƒ๋ฐฐ ๋ฐฐ์†ก

by HandHand 2021. 6. 10.

๋ฌธ์ œ

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

ํ’€์ด ๊ณผ์ •

ํŠน์ • ์‹œ์ž‘ ์ง€์ ์—์„œ ๋ชฉํ‘œ ์ง€์ ์— ๋„๋‹ฌํ•˜๊ธฐ ์œ„ํ•œ ์ตœ์†Œ ๋น„์šฉ์„ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.
๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์„ ์ด์šฉํ•ด์„œ ํ•œ ์ •์ ์—์„œ ๋ชจ๋“  ์ •์ ๊นŒ์ง€์˜ ์ตœ๋‹จ ๋น„์šฉ์„ ๊ตฌํ•˜๋ฉด ElogV ์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋กœ ๊ตฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ


import sys
import heapq


INF = 2e9


def dijkstra(frm, to):
    dist = [INF] * (N + 1)
    pq = []

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

    while pq:
        cost, here = heapq.heappop(pq)

        if dist[here] < cost:
            continue

        for there, there_cost in graph[here]:
            next_cost = cost + there_cost
            if dist[there] > next_cost:
                dist[there] = next_cost
                heapq.heappush(pq, [next_cost, there])

    return dist[to]


def make_graph():
    graph = [[] for _ in range(N + 1)]

    for frm, to, cost in edges:
        graph[frm].append([to, cost])
        graph[to].append([frm, cost])

    return graph


def solution():
    answer = dijkstra(1, N)

    return answer


if __name__ == '__main__':
    N, M = list(map(int, sys.stdin.readline().split()))
    edges = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]

    graph = make_graph()
    answer = solution()

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

๐Ÿ’ฌ ๋Œ“๊ธ€