結果
| 問題 | No.1283 Extra Fee |
| コンテスト | |
| ユーザー |
lam6er
|
| 提出日時 | 2025-03-31 17:25:19 |
| 言語 | PyPy3 (7.3.17) |
| 結果 |
AC
|
| 実行時間 | 869 ms / 2,000 ms |
| コード長 | 2,383 bytes |
| 記録 | |
| コンパイル時間 | 233 ms |
| コンパイル使用メモリ | 96,368 KB |
| 実行使用メモリ | 157,568 KB |
| 最終ジャッジ日時 | 2026-07-08 04:11:51 |
| 合計ジャッジ時間 | 15,358 ms |
|
ジャッジサーバーID (参考情報) |
judge3_0 / judge2_0 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 30 |
ソースコード
import heapq
def main():
import sys
input = sys.stdin.read
data = input().split()
idx = 0
N = int(data[idx])
idx += 1
M = int(data[idx])
idx += 1
fee = [[0]*(N+1) for _ in range(N+1)]
for _ in range(M):
h = int(data[idx])
idx += 1
w = int(data[idx])
idx += 1
c = int(data[idx])
idx += 1
fee[h][w] = c
INF = float('inf')
dist = [[[INF]*(N+1) for _ in range(N+1)] for _ in range(2)]
dist[0][1][1] = 0
heap = []
heapq.heappush(heap, (0, 1, 1, 0))
dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]
while heap:
cost, h, w, used = heapq.heappop(heap)
if h == N and w == N:
print(cost)
return
if cost > dist[used][h][w]:
continue
for dh, dw in dirs:
nh = h + dh
nw = w + dw
if 1 <= nh <= N and 1 <= nw <= N:
current_fee = fee[nh][nw]
new_cost_base = cost + 1
if current_fee > 0:
if used == 0:
# Pay the fee
new_cost = new_cost_base + current_fee
if new_cost < dist[0][nh][nw]:
dist[0][nh][nw] = new_cost
heapq.heappush(heap, (new_cost, nh, nw, 0))
# Skip the fee
new_cost_skip = new_cost_base
if new_cost_skip < dist[1][nh][nw]:
dist[1][nh][nw] = new_cost_skip
heapq.heappush(heap, (new_cost_skip, nh, nw, 1))
else:
# Must pay the fee
new_cost = new_cost_base + current_fee
if new_cost < dist[1][nh][nw]:
dist[1][nh][nw] = new_cost
heapq.heappush(heap, (new_cost, nh, nw, 1))
else:
new_cost = new_cost_base
if new_cost < dist[used][nh][nw]:
dist[used][nh][nw] = new_cost
heapq.heappush(heap, (new_cost, nh, nw, used))
# If exit not reached inside loop, check both states for (N,N)
print(min(dist[0][N][N], dist[1][N][N]))
if __name__ == '__main__':
main()
lam6er