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
๋ฐ์ํ