Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 |
Tags
- 재귀
- 스택
- DP
- 파이썬
- N과M
- 프로그래머스
- 딕셔너리
- dfs
- level1
- 수학
- 가상메모리 관리
- 백준
- programmers
- level3
- 힙
- MYSQL
- level0
- 코딩테스트
- BFS
- 운영체제
- BOJ
- python
- 다익스트라
- 그리디
- 가상메모리
- level2
- 브루트포스
- 구현
- dict
- 다이나믹 프로그래밍
Archives
- Today
- Total
동캄의 코딩도장
백준 14284 [간선 이어가기2] 파이썬 본문
https://www.acmicpc.net/problem/14284
14284번: 간선 이어가기 2
정점 n개, 0개의 간선으로 이루어진 무방향 그래프가 주어진다. 그리고 m개의 가중치 간선의 정보가 있는 간선리스트가 주어진다. 간선리스트에 있는 간선 하나씩 그래프에 추가해 나갈 것이다.
www.acmicpc.net
# 백준 14284 간선 이어가기2
import sys
import heapq
from collections import defaultdict
input = sys.stdin.readline
N, M = map(int, input().split())
graph = defaultdict(list)
for _ in range(M):
a, b, cost = map(int, input().split())
graph[a].append([b, cost])
graph[b].append([a, cost])
def dijkstra(graph, start):
distances = {node: float('inf') for node in range(1, N+1)}
distances[start] = 0
queue = []
heapq.heappush(queue, [distances[start], start])
while queue:
curr_dist, curr_dest = heapq.heappop(queue)
if distances[curr_dest] < curr_dist:
continue
for new_dest, new_dist in graph[curr_dest]:
dist = curr_dist+new_dist
if dist < distances[new_dest]:
distances[new_dest] = dist
heapq.heappush(queue, [dist, new_dest])
return distances
start, end = map(int, input().split())
distances = dijkstra(graph, start)
print(distances[end])
다익스트라를 이용한 문제이다.
'코테 > BOJ' 카테고리의 다른 글
백준 9935 [문자열 폭발] 파이썬 (0) | 2022.05.17 |
---|---|
백준 11909 [배열 탈출] 파이썬 (0) | 2022.05.17 |
백준 17396 [백도어] 파이썬 (0) | 2022.05.17 |
백준 5972 [택배 배송] 파이썬 (0) | 2022.05.17 |
백준 1753 [최단경로] 파이썬 (0) | 2022.05.17 |