[BOJ] 1238. ํํฐ(python)
๐๋ฌธ์
๐ช์์ด๋์ด
๋ค์ต์คํธ๋ผ ๋ง๋ค๊ธฐ
์ฒ์์๋ ๋ง์๋ณ ํํฐ๋ง์๊น์ง ๊ฐ๋ ์ต์ ๊ฒฝ๋ก ๋ฐฐ์ด๊ณผ ํํฐ๋ง์์์ ๊ฐ ๋ง์๋ก ๊ฐ๋ ์ต์ ๊ฒฝ๋ก ๋ฐฐ์ด์ ๊ฐ๊ฐ ๋ง๋ค๋ ค๊ณ ํ๋ค.
๊ทธ๋ฌ๋์๊ฐ๋ณต์ก๋๊ฐ O(๋ง์ ์ * ๋๋ก ์)
์ด๊ณ ์ต๋ ๋ง์ ์๊ฐ 1e3, ์ต๋ ๋๋ก ์๊ฐ 1e4์ผ ๊ฒฝ์ฐ ์๊ฐ์ด๊ณผ๋ผ ๋ค๋ฅธ ๋ฐฉ๋ฒ์ ์ฐพ์๋ค.
๊ฐ ๋ง์๋ณ ๋ค์ต์คํธ๋ผ๋ฅผ ํ๋ฒ ๊ตฌํด์ฃผ๊ณ ๋ค์ต์คํธ๋ผ ๋ฐฐ์ด์ ํ๋์ ๋ฐฐ์ด์ ๋ชจ์ผ๋ฉด ์ด์ฐจ์๋ฐฐ์ด์ด ๋์จ๋ค.ํ์ ์ถ๋ฐ์ง ์ด์ ๋์ฐฉ์ง๋ก ์ต์๋น์ฉ ๊ฐ
์ ์ป์ ์ ์๋ค.์๋ณต ์ค๋ ๊ฑธ๋ฆฌ๋ ํ์ ์ฐพ๊ธฐ
์ต์๋น์ฉ[๋ง์][ํํฐ๋ง์] + ์ต์๋น์ฉ[ํํฐ๋ง์][๋ง์]
์ด ๊ฐ ํ์๋ณ ์๋ณต ์ต์ ๋น์ฉ์ด๊ธฐ ๋๋ฌธ์ ํ์๋ณ๋ก ํ์ํ๋ฉด์ max๊ฐ์ ์ฐพ๋๋ค.๐ฅ์ฝ๋
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
import sys; input = sys.stdin.readline
from collections import defaultdict
from heapq import heappush, heappop
def findRoundTripTime(student):
distance = [float('inf')] * (n+1)
heap = []
distance[student] = 0
heappush(heap,(0,student))
while heap:
cost, cur = heappop(heap)
if distance[cur] < cost: continue
for nxt, t in towns[cur]:
d = t + cost
if distance[nxt] > d:
distance[nxt] = d
heappush(heap,(d,nxt))
return distance
n, m, x = map(int,input().split())
towns = defaultdict(list)
for _ in range(m):
a, b, cost = map(int,input().split())
towns[a].append((b,cost))
dist = [[float('inf') for _ in range(n+1)] for _ in range(n+1)]
for i in range(1,n+1):
dist[i] = findRoundTripTime(i)
answer = 0
for i in range(1,n+1):
answer = max(answer, dist[i][x] + dist[x][i])
print(answer)
Comments powered by Disqus.