Algorithm Problem/Python

[python] ๋ฐฑ์ค€ - 1916. ์ตœ์†Œ๋น„์šฉ ๊ตฌํ•˜๊ธฐ

deo2kim 2020. 11. 27. 09:23
๋ฐ˜์‘ํ˜•

๐Ÿค”๋ฌธ์ œ ํ•ด๊ฒฐ

  • G5 | ๋‹ค์ต์ŠคํŠธ๋ผ

์ •๋ง ๊ธฐ๋ณธ์ ์ธ ๋‹ค์ต์ŠคํŠธ๋ผ ๋ฌธ์ œ!

๋”ฐ๋กœ ํ‚ค ๋ฆฌ์ŠคํŠธ๋ฅผ ์„ค์ •ํ•˜์ง€ ์•Š์•„๋„ ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ๋‹ค.

 

๐Ÿ’ป์†Œ์Šค ์ฝ”๋“œ

import sys
import heapq

input = sys.stdin.readline


def dijkstra(s, e):
    pq = []
    heapq.heappush(pq, (0, s))  # ์ถœ๋ฐœ์ง€๋กœ ๊ฐ€๋Š”๋ฐ 0์›์˜ ๋น„์šฉ
    visited = [0] * (N + 1)
    while pq:
        cost, w = heapq.heappop(pq)
        if w == e:
            return cost

        if visited[w]:
            continue

        visited[w] = 1
        for newt_w, next_cost in adj[w]:
            if not visited[newt_w]:
                heapq.heappush(pq, (cost + next_cost, newt_w))


if __name__ == '__main__':
    N = int(input())  # ๋„์‹œ์˜ ๊ฐœ์ˆ˜
    M = int(input())  # ๋ฒ„์Šค์˜ ๊ฐœ์ˆ˜
    adj = {x + 1: [] for x in range(N)}
    for _ in range(M):
        a, b, c = map(int, input().split())
        adj[a].append((b, c))

    departure, arrival = map(int, input().split())
    answer = dijkstra(departure, arrival)
    print(answer)
 

 

๐Ÿ“•๋ฌธ์ œ ํ™•์ธ

์ถœ์ฒ˜: BACKJOON ONLINE JUDGE

๋งํฌ: https://www.acmicpc.net/problem/1916

 

1916๋ฒˆ: ์ตœ์†Œ๋น„์šฉ ๊ตฌํ•˜๊ธฐ

์ฒซ์งธ ์ค„์— ๋„์‹œ์˜ ๊ฐœ์ˆ˜ N(1 ≤ N ≤ 1,000)์ด ์ฃผ์–ด์ง€๊ณ  ๋‘˜์งธ ์ค„์—๋Š” ๋ฒ„์Šค์˜ ๊ฐœ์ˆ˜ M(1 ≤ M ≤ 100,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์…‹์งธ ์ค„๋ถ€ํ„ฐ M+2์ค„๊นŒ์ง€ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ฒ„์Šค์˜ ์ •๋ณด๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋จผ์ € ์ฒ˜์Œ์—๋Š” ๊ทธ

www.acmicpc.net

 

 

๋ฐ˜์‘ํ˜•