본문 바로가기
알고리즘/[python] 백준 BOJ

[python] 백준 1238 파티

by Alan_Kim 2023. 4. 9.
728x90
반응형

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

 

문제 해결

  • 다익스트라 문제
  • for문을 통해 1~n까지 한 점 i에서 x까지 가는데 최소 시간를 구하고 x에서 i까지 가는데 최소 시간를 구해서 더하면 왕복 최소 시간이 나온다.
  • 리스트를 통해 최댓값을 구하면 된다.

 

CODE

 

import sys
input = sys.stdin.readline
import heapq
INF = sys.maxsize

n, m, x = map(int, input().split())
graph = [[] for _ in range(n+1)]

for _ in range(m):
    start, end, time = map(int, input().split())
    graph[start].append((time, end))

def dijkstra(start):
    heap = []
    record = [INF]*(n+1)
    heapq.heappush(heap, (0,start))
    record[start] = 0
    record[0] = 0
    
    while heap:
        time, now = heapq.heappop(heap)
        if record[now] < time: continue
        for next_time, next_index in graph[now]:
            t = time + next_time
            if record[next_index] > t:
                record[next_index] = t
                heapq.heappush(heap,(t,next_index))
    return record

ans = 0
for i in range(1,n+1):
    go = dijkstra(i)
    back = dijkstra(x)
    ans = max(ans, go[x]+back[i])
print(ans)
728x90
반응형

댓글