-
Notifications
You must be signed in to change notification settings - Fork 0
/
1238-ํํฐ.py
62 lines (43 loc) ยท 1.5 KB
/
1238-ํํฐ.py
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import sys
import heapq
input = sys.stdin.readline
INF = sys.maxsize
N, M, X = map(int, input().split())
graph = [[] for _ in range(N + 1)]
graph_return = [[] for _ in range(N + 1)]
for _ in range(M):
s, e, w = map(int, input().split())
graph[s].append((e, w))
graph_return[e].append((s, w))
def dijkstra(start):
# X ๋ง์์์ ๋์์ค๋ ๊ฒฝ๋ก
distances = [INF] * (N + 1)
distances[start] = 0
heap = []
heapq.heappush(heap, (0, start))
while heap:
dist_to_now, now = heapq.heappop(heap)
if distances[now] < dist_to_now:
continue
for adj, dist_now_to_adj in graph[now]:
dist_to_adj = dist_to_now + dist_now_to_adj
if dist_to_adj < distances[adj]:
distances[adj] = dist_to_adj
heapq.heappush(heap, (dist_to_adj, adj))
# X ๋ง์๋ก ๊ฐ๋ ๊ฒฝ๋ก
distances_reverse = [INF] * (N + 1)
distances_reverse[start] = 0
heap = []
heapq.heappush(heap, (0, start))
while heap:
dist_to_now, now = heapq.heappop(heap)
if distances_reverse[now] < dist_to_now:
continue
for adj, dist_now_to_adj in graph_return[now]:
dist_to_adj = dist_to_now + dist_now_to_adj
if dist_to_adj < distances_reverse[adj]:
distances_reverse[adj] = dist_to_adj
heapq.heappush(heap, (dist_to_adj, adj))
return list(map(sum, zip(distances[1:], distances_reverse[1:])))
result = dijkstra(X)
print(max(result))