Problem solution · Python

ABC021 C — 正直者の高橋くん

ABC021 C — 正直者の高橋くん: 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
83 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 ABC021 C — 正直者の高橋くん, 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

  • 83 lines of Python from the credited upstream file abc021_c.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 codeABC021 C — 正直者の高橋くん · 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)]    path_count = [0 for _ in range(vertex_count)]    path_count[source] = 1    mod = 10 ** 9 + 7     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                 path_count[edge] += path_count[vertex]                path_count[edge] %= mod                 heappush(hq, (new_cost, edge))     return path_count  def main():    import sys     input = sys.stdin.readline     n = int(input())    a, b = map(int, input().split())    a -= 1    b -= 1    m = int(input())    edges = [[] for _ in range(n)]     for _ in range(m):        xi, yi = map(int, input().split())        xi -= 1        yi -= 1        # ci: cost        # xi: edge (0-indexed)        # yi: edge (0-indexed)        edges[xi].append((1, yi))        edges[yi].append((1, xi))     path_counts = dijkstra(vertex_count=n, source=a, edges=edges)     print(path_counts[b])  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 ↗