Post

[BOJ] 1238. ํŒŒํ‹ฐ(python)

๐Ÿ“Œ๋ฌธ์ œ

Alt text

๐Ÿ’ช์•„์ด๋””์–ด

  1. ๋‹ค์ต์ŠคํŠธ๋ผ ๋งŒ๋“ค๊ธฐ
    ์ฒ˜์Œ์—๋Š” ๋งˆ์„๋ณ„ ํŒŒํ‹ฐ๋งˆ์„๊นŒ์ง€ ๊ฐ€๋Š” ์ตœ์†Œ ๊ฒฝ๋กœ ๋ฐฐ์—ด๊ณผ ํŒŒํ‹ฐ๋งˆ์„์—์„œ ๊ฐ ๋งˆ์„๋กœ ๊ฐ€๋Š” ์ตœ์†Œ ๊ฒฝ๋กœ ๋ฐฐ์—ด์„ ๊ฐ๊ฐ ๋งŒ๋“ค๋ ค๊ณ ํ–ˆ๋‹ค.
    ๊ทธ๋Ÿฌ๋‚˜ ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ O(๋งˆ์„ ์ˆ˜ * ๋„๋กœ ์ˆ˜)์ด๊ณ  ์ตœ๋Œ€ ๋งˆ์„ ์ˆ˜๊ฐ€ 1e3, ์ตœ๋Œ€ ๋„๋กœ ์ˆ˜๊ฐ€ 1e4์ผ ๊ฒฝ์šฐ ์‹œ๊ฐ„์ดˆ๊ณผ๋ผ ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์„ ์ฐพ์•˜๋‹ค.
    ๊ฐ ๋งˆ์„๋ณ„ ๋‹ค์ต์ŠคํŠธ๋ผ๋ฅผ ํ•œ๋ฒˆ ๊ตฌํ•ด์ฃผ๊ณ  ๋‹ค์ต์ŠคํŠธ๋ผ ๋ฐฐ์—ด์„ ํ•˜๋‚˜์˜ ๋ฐฐ์—ด์— ๋ชจ์œผ๋ฉด ์ด์ฐจ์›๋ฐฐ์—ด์ด ๋‚˜์˜จ๋‹ค. ํ–‰์€ ์ถœ๋ฐœ์ง€ ์—ด์€ ๋„์ฐฉ์ง€๋กœ ์ตœ์†Œ๋น„์šฉ ๊ฐ’์„ ์–ป์„ ์ˆ˜ ์žˆ๋‹ค.

  2. ์™•๋ณต ์˜ค๋ž˜ ๊ฑธ๋ฆฌ๋Š” ํ•™์ƒ ์ฐพ๊ธฐ
    ์ตœ์†Œ๋น„์šฉ[๋งˆ์„][ํŒŒํ‹ฐ๋งˆ์„] + ์ตœ์†Œ๋น„์šฉ[ํŒŒํ‹ฐ๋งˆ์„][๋งˆ์„]์ด ๊ฐ ํ•™์ƒ๋ณ„ ์™•๋ณต ์ตœ์†Œ ๋น„์šฉ์ด๊ธฐ ๋•Œ๋ฌธ์— ํ•™์ƒ๋ณ„๋กœ ํƒ์ƒ‰ํ•˜๋ฉด์„œ 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)
This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.