Problem solution · Python

ABC342 E — Last Train

ABC342 E — Last 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 ABC342 E — Last 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 abc342_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 codeABC342 E — Last Train · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*-  def main():    import sys    from heapq import heappop, heappush     input = sys.stdin.readline     n, m = map(int, input().split())    edges = [[] for _ in range(n)]     for _ in range(m):        li, di, ki, ci, to, bi = map(int, input().split())        to -= 1        bi -= 1         # 頂点Nから見るため、逆向きに辺を張る        edges[bi].append((to, li, di, ki, ci))     inf = 10**19    hq = [(-inf, n - 1)]  # weight, vertex number (0-indexed)    ts = [-inf] * n    ts[-1] = inf     while hq:        ti, vertex = heappop(hq)        ti = -ti         if ti != ts[vertex]:            continue         for to, li, di, ki, ci in edges[vertex]:            nt = ti - ci             if li > nt:                continue             k_candidate = (nt - li) // di            k_candidate = min(k_candidate, ki - 1)            new_cost = li + k_candidate * di             if new_cost <= ts[to]:                continue             ts[to] = new_cost            heappush(hq, (-new_cost, to))     for ti in ts[:-1]:        if ti == -inf:            ti = "Unreachable"         print(ti)  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 ↗