Skip to content

Instantly share code, notes, and snippets.

@wonderful-panda
Created April 13, 2021 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wonderful-panda/2aaac4efdf59fab688d5dde65df9fd0c to your computer and use it in GitHub Desktop.
Save wonderful-panda/2aaac4efdf59fab688d5dde65df9fd0c to your computer and use it in GitHub Desktop.
import heapq
from typing import List, Tuple
def calc_costs(N: int, MAP: List[Tuple[int, int]], start: int) -> List[int]:
"""
指定された都市から各都市への最小コストを計算する
MAP: list of { index: 都市, value: (行先の都市, コスト) }
"""
costs = [-1] * N
# queueの要素は (その都市への最小コスト, 都市)
# コストの小さい順に取り出すためにコストをtupleの先頭にもってくる
queue = [(0, start)]
heapq.heapify(queue)
while len(queue) > 0:
cost, city = heapq.heappop(queue)
if costs[city] >= 0:
continue
costs[city] = cost
for next_city, next_cost in MAP[city]:
if costs[next_city] < 0:
heapq.heappush(queue, (cost + next_cost, next_city))
return costs
def solve(N, MAP):
costs_from_start = calc_costs(N, MAP, 0)
costs_from_goal = calc_costs(N, MAP, N - 1)
for day in range(N):
print(costs_from_start[day] + costs_from_goal[day])
def main():
N, M = [int(v) for v in input().split(' ')]
MAP = [[] for v in range(N)]
for _ in range(M):
a, b, c = [int(v) for v in input().split(' ')]
MAP[a - 1].append((b - 1, c))
MAP[b - 1].append((a - 1, c))
solve(N, MAP)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment