結果

問題 No.1283 Extra Fee
ユーザー lam6er
提出日時 2025-03-31 17:25:19
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,401 ms / 2,000 ms
コード長 2,383 bytes
コンパイル時間 533 ms
コンパイル使用メモリ 82,664 KB
実行使用メモリ 141,456 KB
最終ジャッジ日時 2025-03-31 17:26:13
合計ジャッジ時間 21,031 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 30
権限があれば一括ダウンロードができます

ソースコード

diff #

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()
0