結果

問題 No.3111 Toll Optimization
ユーザー keigo kuwata
提出日時 2025-04-20 17:31:28
言語 Python3
(3.13.1 + numpy 2.2.1 + scipy 1.14.1)
結果
AC  
実行時間 2,529 ms / 5,000 ms
コード長 2,024 bytes
コンパイル時間 447 ms
コンパイル使用メモリ 12,288 KB
実行使用メモリ 117,712 KB
最終ジャッジ日時 2025-04-20 17:32:17
合計ジャッジ時間 48,515 ms
ジャッジサーバーID
(参考情報)
judge3 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 70
権限があれば一括ダウンロードができます

ソースコード

diff #

import heapq

def solve(N, M, K, costs, edges):
    # 隣接リストの作成
    graph = [[] for _ in range(N+1)]
    for i, (u, v) in enumerate(edges):
        graph[u].append((v, costs[i]))
        graph[v].append((u, costs[i]))  # 双方向
    
    # 距離配列 (町, 残りクーポン) -> 最小コスト
    # 初期値は無限大
    dist = {}
    for i in range(1, N+1):
        for j in range(K+1):
            dist[(i, j)] = float('inf')
    
    # 始点の設定
    dist[(1, K)] = 0
    
    # 優先度付きキュー (コスト, 町, 残りクーポン)
    pq = [(0, 1, K)]
    
    while pq:
        cost, node, remaining_coupons = heapq.heappop(pq)
        
        # 既に見つかっている最短経路よりコストが高い場合はスキップ
        if cost > dist[(node, remaining_coupons)]:
            continue
        
        # 目的地に到着した場合
        if node == N:
            return cost
        
        # 隣接ノードを探索
        for next_node, edge_cost in graph[node]:
            # クーポンを使わない場合
            new_cost = cost + edge_cost
            if new_cost < dist[(next_node, remaining_coupons)]:
                dist[(next_node, remaining_coupons)] = new_cost
                heapq.heappush(pq, (new_cost, next_node, remaining_coupons))
            
            # クーポンを使う場合
            if remaining_coupons > 0:
                new_cost = cost  # クーポンを使うとコストは0
                if new_cost < dist[(next_node, remaining_coupons-1)]:
                    dist[(next_node, remaining_coupons-1)] = new_cost
                    heapq.heappush(pq, (new_cost, next_node, remaining_coupons-1))
    
    # 到達不可能な場合
    return -1

# 入力処理
N, M, K = map(int, input().split())
costs = list(map(int, input().split()))
edges = []
for _ in range(M):
    u, v = map(int, input().split())
    edges.append((u, v))

# 解を求める
result = solve(N, M, K, costs, edges)
print(result)
0