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 | 31 |
Tags
- 다익스트라
- 자료구조
- 플로이드-워셜
- 그리디
- MST
- 다이나믹프로그래밍
- DP
- 그래프 이론
- join
- 에라토스테네스의 체
- 해시
- 브루트포스
- 백트래킹
- 구현
- 수학
- 시뮬레이션
- 분할정복
- 다이나믹 프로그래밍
- DFS
- 재귀
- 우선순위큐
- BFS
- 서브쿼리
- 크루스칼
- 누적합
- 투포인터
- GROUP BY
- 다시
- 트리
- 그래프 탐색
Archives
- Today
- Total
기록하고 까먹지 말기
1916 본문
날짜 : 2023. 03. 13
사용 언어 : python
문제
코드
import sys
import heapq
n = int(sys.stdin.readline()) # 도시의 개수
m = int(sys.stdin.readline()) # 버스의 개수
graph = [[] for _ in range(n + 1)] # 전체 그래프 (0은 생략)
dist = [int(1e9)] * (n + 1) # 기준 노드에서 각 노드까지 길이(start 기준)
for _ in range(m):
s, e, c = map(int, sys.stdin.readline().split()) # 시작, 도착, 비용
graph[s].append([e, c]) # s -> e까지의 비용 c 추가
#for i in graph: print(i)
def dijkstra(start):
q = list()
heapq.heappush(q, (0, start)) # 거리, 노드번호
dist[start] = 0
while q:
d, now = heapq.heappop(q) # start 에서 now 까지의 거리
#print("%d에서 %d까지 확인"%(start, now))
if dist[now] < d : continue # 최신화 필요 없는 경우
for node in graph[now]: # now 노드 연결 노드 탐색 [노드번호, cost]
cost = d + node[1] # 거쳐서 가는 경우
if cost < dist[node[0]]: # 인접노드간 최단거리 최신화
dist[node[0]] = cost
heapq.heappush(q, (cost, node[0]))
#print(q)
return
s, e = map(int, sys.stdin.readline().rstrip().split()) # 시작, 도착지점 입력
dijkstra(s)
print(dist[e])
풀이
- 다익스트라를 활용하여 풀이하는 문제였다.
알게된 점
-
참고 사이트
- https://techblog-history-younghunjo1.tistory.com/248
[Python] 우선순위 큐를 활용한 개선된 다익스트라(Dijkstra) 알고리즘
🔊 이번 포스팅에는 최근에 Python으로 알고리즘을 공부하기 시작하면서 알게 된 여러 알고리즘의 원리와 Python으로 구현하는 방법에 대해 소개해보려 한다. 필자는 최근 알고리즘 공부를 '나동
techblog-history-younghunjo1.tistory.com