easysheep 2023. 4. 6. 17:23

1. 문제 출처

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

2. 풀이

각 노드를 시작점으로 경로를 구해줘야 한다.

 

import heapq
# 입력
n,m,x = map(int, input().split())

graph = [[] for _ in range(n+1)]
distance = [[float('inf')] * (n+1) for _ in range(n+1)]

# 입력
for _ in range(m):
    start , end , cost = map(int, input().split())
    graph[start].append([cost , end])
 
# 데이크스트라 알고리즘 
def di(start):
    q = []
    heapq.heappush(q,[0,start])
    distance[start][start] = 0
    
    while q:
        dist, node = heapq.heappop(q)
        if distance[start][node] < dist:
            continue
            
        for w,n in graph[node]:
            cost = dist+ w
            if distance[start][n]>cost:
                distance[start][n] = cost
                heapq.heappush(q,[cost,n])
                

def solution():
    # 모든 경로에 따라 데아크스트라 알고리즘을 통해 비용을 구한다.
    for i in range(1,n+1):
        di(i)
    result = []
    # 왕복거리 리스트를 구한다.
    for i in range(1,n+1):
        if i == x: 
            continue
        result.append(distance[x][i] + distance[i][x])
    print(max(result))    

solution()