๐Ÿ—๏ธ Algorithm/๐ŸŸฉ ๋ฐฑ์ค€

๐ŸŸฉ [๋ฐฑ์ค€] [Python] [Gold3] 1238๋ฒˆ_ํŒŒํ‹ฐ

Dbswnstjd 2023. 5. 9. 12:31

๋ฌธ์ œ

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

ํ’€์ด

# ๋ฐฑ์ค€ 1238๋ฒˆ ๋ฌธ์ œ - ํŒŒํ‹ฐ
import heapq
n, m, x = map(int, input().split())
# n: ๋…ธ๋“œ, m: ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜
# ๋ชจ๋“  ํ•™์ƒ x์— ๊ฐˆ ์ˆ˜ ์žˆ๊ณ  x์—์„œ ์ง‘์œผ๋กœ ๋Œ์•„์˜ฌ ์ˆ˜ ์žˆ๋Š” ๋ฐ์ดํ„ฐ๋งŒ ์ž…๋ ฅ
graph = [[] for _ in range(n+1)]
for _ in range(m):
    a, b, cost = map(int, input().split())
    graph[a].append((b,cost))

def dijkstra(start):
    q = []
    distance = [1e9] * (n+1)
    heapq.heappush(q, (0, start))
    distance[start] = 0

    while q:
        dist, now = heapq.heappop(q)
        if distance[now] < dist:
            continue

        for i in graph[now]:
            cost = dist + i[1]

            if distance[i[0]] > cost:
                distance[i[0]] = cost
                heapq.heappush(q, (cost, i[0]))
    return distance
result = 0
for i in range(1,n+1):
    go = dijkstra(i)
    back = dijkstra(x)
    result = max(result, go[x] + back[i])
    
print(result)

์ตœ๋‹จ๊ฒฝ๋กœ๋ฅผ ๊ตฌํ•˜๋Š” ๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ด์šฉํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

x๋กœ ๊ฐ€๋Š” ์ตœ๋‹จ๋น„์šฉ๊ณผ ๋‹ค์‹œ ์ง‘์œผ๋กœ ๋Œ์•„์˜ค๋Š” ์ตœ๋‹จ๋น„์šฉ์„ ๋”ํ•˜์—ฌ ๊ฐ€์žฅ ํฐ ๊ฐ’์„ ๊ตฌํ•˜๋ฉด ๋œ๋‹ค.