Problem solution · Python

ABC340 D — Super Takahashi Bros.

ABC340 D — Super Takahashi Bros.: 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
75 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 ABC340 D — Super Takahashi Bros., 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

  • 75 lines of Python from the credited upstream file abc340_d.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 codeABC340 D — Super Takahashi Bros. · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*-  def dijkstra(vertex_count: int, source: int, edges):    """Uses Dijkstra's algorithm to find the shortest path in a graph.     Args:        vertex_count: The number of vertices.        source      : Vertex number (0-indexed).        edges       : List of (cost, edge) (0-indexed).     Returns:        costs  : List of the shortest distance.        parents: List of parent vertices.     Landau notation: O(|Edges|log|Vertices|).     See:    https://atcoder.jp/contests/abc191/submissions/19964078    https://atcoder.jp/contests/abc191/submissions/19966232    """     from heapq import heappop, heappush     hq = [(0, source)]  # weight, vertex number (0-indexed)    costs = [float("inf") for _ in range(vertex_count)]    costs[source] = 0    visited = [False for _ in range(vertex_count)]    pending = -1    parents = [pending for _ in range(vertex_count)]     while hq:        cost, vertex = heappop(hq)         if cost > costs[vertex]:            continue         if visited[vertex]:            continue         visited[vertex] = True         for weight, edge in edges[vertex]:            new_cost = cost + weight             if new_cost < costs[edge]:                costs[edge] = new_cost                parents[edge] = vertex                heappush(hq, (new_cost, edge))     return costs, parents  def main():    import sys     input = sys.stdin.readline     n = int(input())    edges = [[] for _ in range(n)]     for i in range(n - 1):        ai, bi, xi = map(int, input().split())        xi -= 1         edges[i].append((ai, i + 1))        edges[i].append((bi, xi))     dist, _ = dijkstra(vertex_count=n, source=0, edges=edges)    print(dist[-1])  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 ↗