Skip to content

Commit 1272dfc

Browse files
committed
b1238 - 파티 : 최소힙 다익스트라
1 parent b011734 commit 1272dfc

File tree

1 file changed

+26
-16
lines changed
  • Baekjoon/Python/ShortestPath/1238번: 파티

1 file changed

+26
-16
lines changed

Baekjoon/Python/ShortestPath/1238번: 파티/파티.py

Lines changed: 26 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -17,35 +17,45 @@
1717
각 노드가 노드 X를 거쳐 돌아오는 최단 거리 중 그 거리가 가장 긴 거리 출력
1818
1919
플루이드 워셜 이용 모든 정점에 대한 최단거리 정의 -> 시간 초과 -> 1000 ** 3
20+
-> 다익스트라를 이용해야 함
2021
'''
2122

22-
import sys
23+
import sys, heapq
2324
input = sys.stdin.readline
2425

25-
INF = int(1e9) # 무한을 의미하는 상수
26-
27-
def floyd_warshall(graph, n):
28-
for k in range(1, n + 1):
29-
for a in range(1, n + 1):
30-
for b in range(1, n + 1):
31-
graph[a][b] = min(graph[a][b], graph[a][k] + graph[k][b])
26+
INF = int(1e9) #무한을 의미하는 상수
27+
28+
def dijkstra(graph, start, distance):
29+
q = []
30+
heapq.heappush(q, (0, start))
31+
distance[start] = 0
32+
while q:
33+
dist, now = heapq.heappop(q)
34+
if distance[now] < dist:
35+
continue
36+
for i in graph[now]:
37+
cost = distance[now] + i[1]
38+
if cost < distance[i[0]]:
39+
distance[i[0]] = cost
40+
heapq.heappush(q, (cost, i[0]))
3241

3342
N, M, X = map(int, input().split())
3443

35-
g = [[INF] * (N + 1) for _ in range(N + 1)]
36-
37-
# 자기 자신에서 자기 자신으로 가는 비용은 0으로 초기화
38-
for a in range(1, N + 1):
39-
g[a][a] = 0
44+
g = [[] for _ in range(N + 1)]
45+
distance = [[INF] * (N + 1) for _ in range(N + 1)]
4046

4147
for i in range(M):
4248
s, e, t = map(int, input().split())
43-
g[s][e] = t
49+
g[s].append((e, t))
4450

45-
floyd_warshall(g, N)
51+
dijkstra(g, X, distance[X])
52+
for i in range(1, N + 1):
53+
dijkstra(g, i, distance[i])
4654

4755
cost = [0 for _ in range(N + 1)]
4856
for i in range(1, N + 1):
49-
cost[i] = g[i][X] + g[X][i]
57+
cost[i] = distance[X][i] + distance[i][X]
58+
if (cost[i] > INF) :
59+
cost[i] = -1
5060

5161
print(max(cost))

0 commit comments

Comments
 (0)