Problem solution · Python

ABC192 E — Train

ABC192 E — Train: a Python solution using heap or priority queue. Learn the idea, check the complexity, and read the full code, with credit to KATO-Hiro AtCoder Solutions.

Technique
Heap or priority queue
Source
KATO-Hiro AtCoder Solutions
Length
58 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Heap or priority queue

For ABC192 E — Train, the implementation repeatedly takes the currently best candidate from a heap while inserting newly available choices.

  1. Define the priority key and whether the smallest or largest item should lead.
  2. Push each candidate when it becomes eligible.
  3. Discard stale entries when necessary and process the best live candidate.

Code notes

  • 58 lines of Python from the credited upstream file abc192_e.py.
  • The implementation visibly relies on sequence storage, ordered lookup, work queue.
  • No explicit loop blocks detected.

Complexity

Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from KATO-Hiro AtCoder Solutions by KATO-Hiro and is used under the CC0-1.0 licence.

Full codeABC192 E — Train · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*-  def dijkstra(vertex_count: int, source: int, edges):    from heapq import heappop, heappush     hq = [(0, source)]  # weight, vertex number (0-indexed)    costs = [float("inf") for _ in range(vertex_count)]    costs[source] = 0    pending = -1    parents = [pending for _ in range(vertex_count)]     while hq:        cost, vertex = heappop(hq)         if cost > costs[vertex]:            continue         for weight, edge, dep_time in edges[vertex]:            new_cost = cost + ((dep_time - cost) % dep_time) + weight             if new_cost < costs[edge]:                costs[edge] = new_cost                parents[edge] = vertex                heappush(hq, (new_cost, edge))     return costs  def main():    import sys     input = sys.stdin.readline     n, m, x, y = map(int, input().split())    edges = [[] for _ in range(n)]    x -= 1    y -= 1     for _ in range(m):        ai, bi, ti, ki = map(int, input().split())        ai -= 1        bi -= 1        edges[ai].append((ti, bi, ki))        edges[bi].append((ti, ai, ki))     dist = dijkstra(vertex_count=n, source=x, edges=edges)    ans = dist[y]     if ans == float("inf"):        ans = -1     print(ans)  if __name__ == "__main__":    main() 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗