코딩하는 해맑은 거북이
[Python] 파티 - 백준 (최단경로) 본문
해당 글은 백준 1238번 '파티' 문제를 다룬다.
문제
https://www.acmicpc.net/problem/1238
1238번: 파티
첫째 줄에 N(1 ≤ N ≤ 1,000), M(1 ≤ M ≤ 10,000), X가 공백으로 구분되어 입력된다. 두 번째 줄부터 M+1번째 줄까지 i번째 도로의 시작점, 끝점, 그리고 이 도로를 지나는데 필요한 소요시간 Ti가 들어
www.acmicpc.net
설명
해당 문제는 최단 경로를 구하는 알고리즘 중 다익스트라를 활용하면 된다.
x까지 가는 최단 경로와 x에서 집으로 돌아오는 최단 경로를 2번의 다익스트라로 구할 수 있다.
코드
import heapq
import sys
input = sys.stdin.readline
INF = int(1e9)
n, m, x = map(int, input().split())
graph = [[] for _ in range(n+1)]
for _ in range(m):
s, e, t = map(int, input().split())
graph[s].append((e, t))
def dijkstra(start, end):
distance = [INF]*(n+1)
distance[start]= 0
q = []
heapq.heappush(q, (0, start))
while q:
dist, now = heapq.heappop(q)
if distance[now] < dist:
continue
for next_n, next_dist in graph[now]:
cost = dist + next_dist
if cost < distance[next_n]:
distance[next_n] = cost
heapq.heappush(q, (cost, next_n))
return distance[end]
result = []
for i in range(1, n+1):
result.append(dijkstra(i, x)+dijkstra(x, i))
print(max(result))
'코딩테스트' 카테고리의 다른 글
[Python] 거짓말 - 백준 (0) | 2023.09.01 |
---|---|
[Python] 네트워크 연결 - 백준 (MST) (0) | 2023.08.30 |
[Python] 접두사 - 백준 (0) | 2023.08.27 |
[Python] 노드사이의 거리 - 백준 (BFS) (0) | 2023.08.26 |
[Python] 보물섬 - 백준 (BFS) (0) | 2023.08.25 |
Comments