[백준] 1238번 파티

JaeYeop·2022년 4월 6일
0

백준

목록 보기
2/19

[문제]

https://www.acmicpc.net/problem/1238

[코드]

import sys
import heapq
INF = int(1e9)
input = sys.stdin.readline

n, m, x = map(int, input().split())
graph = [[] for i in range(n+1)]
for i in range(m):
    a, b, c = map(int, input().split())
    graph[a].append([b,c])
distance = [INF] * (n + 1)

def dijkstra(start):
    heap = []

    heapq.heappush(heap, [0, start])
    distance[start] = 0
    while heap:
        dist, now = heapq.heappop(heap)
        if distance[now] < dist:
            continue
        for i in graph[now]:
            cost = dist + i[1]
            if cost < distance[i[0]]:
                distance[i[0]] = cost
                heapq.heappush(heap, [cost, i[0]])

dijkstra(x)
res_go = distance
for i in range(1, n + 1):
    distance = [INF] * (n + 1)
    dijkstra(i)
    res_go[i] += distance[x]

print(max(res_go[1:]))

[풀이]

다익스트라를 활용하여 x에서 각자의 집까지 거리 'x->집'을 구한다

반대로 1번 학생부터 집에서 x까지 '집->x'를 'x->집'과 더한다. 이러면 왕복 거리를 구할 수 있다

범위 1부터 끝까지 max값을 출력한다

profile
이게 왜 틀리지... (나의 메모용 블로그)

0개의 댓글