[파이썬] 백준 10776 : 제국 (골드1)
풀이
방향성 생각
- 같은 node라도 현재 뗏목의 상태에 따라서 다른 상태로 취급한다.
- V에 사용되는 state를 node, hp로 만든다. (입력이 작게 주어지는 이유가 있다. 차원 늘리라고)
전체코드
import sys
import heapq as hq
input = lambda : sys.stdin.readline().strip()
INF = float('inf')
# 그래프 추가
K,N,M = map(int,input().split())
G = [[] for _ in range(N+1)]
for _ in range(M):
a,b,t,h = map(int,input().split())
G[a].append((b,t,h))
G[b].append((a,t,h))
start,end = map(int,input().split())
V = [[INF]*(N+1) for _ in range(K+1)]
V[K][start] = 0
# 다익스트라
heap = [(0,K,start)]
while heap:
t,hp,x = hq.heappop(heap)
if t > V[hp][x]:
continue
for nx,cost,dmg in G[x]:
nt = t + cost
nhp = hp - dmg
if nhp >= 1 and nt < V[nhp][nx]:
hq.heappush(heap,(nt,nhp,nx))
V[nhp][nx] = nt
answer = list(V[i][end] for i in range(1,K+1) if V[i][end] != INF)
print(min(answer) if answer else -1)
코멘트
- 빡구현도 아니고 함수 쓰는걸 선호하지는 않는데, 이런 최단경로 탐색 문제에서는 리턴시키는게 확실히 빠르다.
'Algorithm > Graph' 카테고리의 다른 글
[파이썬] 백준 30894 : 유령의 집 탈출하기 (골드1) (0) | 2025.03.03 |
---|---|
[파이썬] 백준 18128 : 치삼이의 징검다리 건너기 (골드1) (0) | 2025.03.03 |
[파이썬] 백준 15906 : 변신 이동 게임 (골드1) (0) | 2025.03.03 |
[파이썬] 백준 18224 : 미로에 갇힌 건우 (골드1) (0) | 2025.03.01 |
[파이썬, 자바] 백준 28707 : 배열 정렬 (골드1) (0) | 2025.02.27 |
[파이썬] 백준 16118 : 달빛 여우 (골드1) (0) | 2025.02.24 |
[파이썬, 자바] 백준 1559 : 놀라운 미로 (플레5) (0) | 2025.02.23 |
댓글