나의 풀이
from collections import deque
import sys
def _back_home(pt_h, n, conn_dict):
answer = [False] * n
answer[pt_h - 1] = 0
queue = deque([(pt_h, 0)])
while queue:
now_point, now_cost = queue.popleft()
for next_point, next_cost in conn_dict[now_point]:
if (answer[next_point - 1] is False) or (answer[next_point - 1] > now_cost + next_cost):
answer[next_point - 1] = (now_cost + next_cost)
queue.append((next_point, now_cost + next_cost))
return answer
def _go_pt(n, start_point, pt_h, conn_dict):
answer = [False] * n
answer[start_point - 1] = 0
queue = deque([(start_point, 0)])
while queue:
now_point, now_cost = queue.popleft()
for next_point, next_cost in conn_dict[now_point]:
if (answer[next_point - 1] is False) or (answer[next_point - 1] > now_cost + next_cost):
answer[next_point - 1] = (now_cost + next_cost)
queue.append((next_point, now_cost + next_cost))
return answer[pt_h - 1]
def _main(n, pt_h, conn_dict):
answer = [0] * n
go_pt = [0] * n
for i in range(1, n+1):
go_pt[i - 1] = _go_pt(n, i, pt_h, conn_dict)
back_pt = _back_home(pt_h, n, conn_dict)
for idx in range(n):
answer[idx] = go_pt[idx] + back_pt[idx]
return max(answer)
n, m, x = map(int, sys.stdin.readline().rstrip().split())
conn_dict = {i: [] for i in range(1, n + 1)}
for _ in range(m):
start, end, cost = map(int, sys.stdin.readline().rstrip().split())
conn_dict[start].append((end, cost))
print(_main(n, x, conn_dict))
시간 복잡도
for i in range(1, n+1) : 각 마을 순회 ( 선형 시간 복잡도 )
_go_pt(n, i, pt_h, conn_dict) : 각 마을 그래프 탐색 ( 선형 시간 복잡도 )
해당 알고리즘 시간 복잡도 : 이차형 시간 복잡도 ( O(n ** 2) )'코딩테스트 파이썬 > 백준' 카테고리의 다른 글
| 파이프 옮기기 1 ( 17070번 ) (0) | 2025.02.27 |
|---|---|
| 숨박꼭질 3 ( 13549번 ) (0) | 2025.02.21 |
| 서강그라운드 ( 14938 ) (0) | 2025.02.20 |
| 교수님 저는 취업할래요 ( 18221 ) (0) | 2025.02.18 |
| 연구소 ( 14502번 ) (0) | 2025.02.11 |