코드
import sys, heapq
input = sys.stdin.readline
INF = 987654321
n,m = map(int, input().split())
graph = [[] for _ in range(n+1)]
visited = [INF]*(n+1)
for _ in range(m):
a,b,c = map(int, input().split())
graph[a].append((b,c))
graph[b].append((a,c))
def dijkstra():
queue = [(0,1)]
visited[1] = 0
while queue:
cost, vertex = heapq.heappop(queue)
if cost > visited[vertex]: continue
for ver in graph[vertex]:
ncost = cost + ver[1]
if visited[ver[0]]>ncost:
visited[ver[0]] = ncost
heapq.heappush(queue, (ncost,ver[0]))
return visited[n]
print(dijkstra())
전형적인 다익스트라 알고리즘 문제
'백준' 카테고리의 다른 글
[백준] 2252번 줄 세우기 파이썬 코드 (0) | 2023.12.31 |
---|---|
[백준] 1005번 ACM CRAFT 파이썬 코드 (1) | 2023.12.30 |
[백준] 2224번 명제 증명 파이썬 코드 (0) | 2023.12.30 |
[백준] 1092번 배 파이썬 코드 (1) | 2023.12.29 |
[백준] 2206번 벽 부수고 이동하기 파이썬 코드 (0) | 2023.12.27 |
코드
import sys, heapq
input = sys.stdin.readline
INF = 987654321
n,m = map(int, input().split())
graph = [[] for _ in range(n+1)]
visited = [INF]*(n+1)
for _ in range(m):
a,b,c = map(int, input().split())
graph[a].append((b,c))
graph[b].append((a,c))
def dijkstra():
queue = [(0,1)]
visited[1] = 0
while queue:
cost, vertex = heapq.heappop(queue)
if cost > visited[vertex]: continue
for ver in graph[vertex]:
ncost = cost + ver[1]
if visited[ver[0]]>ncost:
visited[ver[0]] = ncost
heapq.heappush(queue, (ncost,ver[0]))
return visited[n]
print(dijkstra())
전형적인 다익스트라 알고리즘 문제
'백준' 카테고리의 다른 글
[백준] 2252번 줄 세우기 파이썬 코드 (0) | 2023.12.31 |
---|---|
[백준] 1005번 ACM CRAFT 파이썬 코드 (1) | 2023.12.30 |
[백준] 2224번 명제 증명 파이썬 코드 (0) | 2023.12.30 |
[백준] 1092번 배 파이썬 코드 (1) | 2023.12.29 |
[백준] 2206번 벽 부수고 이동하기 파이썬 코드 (0) | 2023.12.27 |