Notice
Recent Posts
Recent Comments
Link
나의 개발일지
[백준] 1238 파티 [Python, 파이썬] 본문
- 문제 : https://www.acmicpc.net/problem/1238
- 🔑 다익스트라
- 각 마을에서 도착지까지의 거리를 저장 [INF, 1, 0, 3, 7]
- 도착지에서 각 마을까지의 거리를 저장 [ 0, 4, 0, 6, 3]
- 그래서 총 n번의 다익스트라를 진행
- 0번 인덱스 제외 각 인덱스의 합이 가장 큰 거리가 정답
from collections import defaultdict
from heapq import heappush, heappop
n, m, x = map(int, input().split()) # n명 학생(마을), m개의 단방향 도로, x도착지
graph = defaultdict(list)
for i in range(m):
s, e, t = map(int, input().split())
graph[s].append((t, e)) # 거리, 도착지 순서
def dijkstra(start):
distance = [INF] * (n+1)
distance[start] = 0
q = []
heappush(q, (0, start)) # 거리, 시작위치
while q:
now_distance, now_node = heappop(q)
if now_distance > distance[now_node]:
continue
for next_distance, next_node in graph[now_node]:
new_distance = now_distance + next_distance
if distance[next_node] > new_distance:
distance[next_node] = new_distance
heappush(q, (new_distance, next_node))
sum_distance[start] = distance[x] # 출발 마을에서 도착 마을까지의 최소 거리를 저장
return distance
INF = int(1e9)
sum_distance = [0] * (n+1)
x_distance = []
for i in range(1, n+1):
if i == x:
x_distance = dijkstra(i) # 도착지에서 각 마을로 가는 최소 거리를 저장
else:
dijkstra(i)
answer = -1
for i in range(1, n+1): # 왕복 거리가 가장 긴 마을 구하기
answer = max(answer, x_distance[i] + sum_distance[i])
print(answer)
'백준' 카테고리의 다른 글
[백준] 1654 랜선 자르기 [Python, 파이썬] (1) | 2023.11.03 |
---|---|
[백준] 1655 가운데를 말해요 [Python, 파이썬] (1) | 2023.11.03 |
[백준] 5557 1학년 [Python, 파이썬] (1) | 2023.10.24 |
[백준] 24479 알고리즘 수업 - 깊이 우선 탐색 1 [Python, 파이썬] (1) | 2023.10.21 |
[백준] 11725 트리의 부모 찾기 [Python, 파이썬] (0) | 2023.10.21 |
Comments