- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 98 lines of Python from the credited upstream file ccc25s4.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.
Use this to learn the idea, then write your own version.
123 4import heapq5 67N, M = map(int, input().split())8 910levels = [set() for _ in range(N)]11tunnels = []12 1314for _ in range(M):15 a, b, c = map(int, input().split())16 a -= 1 17 b -= 118 tunnels.append((a, b, c))19 levels[a].add(c)20 levels[b].add(c)21 2223levels[0].add(0)24 2526for i in range(N):27 levels[i] = sorted(levels[i])28 2930offset = [0] * (N + 1)31total_nodes = 032for i in range(N):33 offset[i] = total_nodes34 total_nodes += len(levels[i])35offset[N] = total_nodes36 3738maps = []39for i in range(N):40 d = {}41 for j, val in enumerate(levels[i]):42 d[val] = j43 maps.append(d)44 4546graph = [[] for _ in range(total_nodes)]47 4849for i in range(N):50 base = offset[i]51 L = levels[i]52 for j in range(len(L) - 1):53 u = base + j54 v = base + j + 155 diff = L[j+1] - L[j]56 graph[u].append((v, diff))57 graph[v].append((u, diff))58 5960for a, b, c in tunnels:61 u = offset[a] + maps[a][c]62 v = offset[b] + maps[b][c]63 graph[u].append((v, 0))64 graph[v].append((u, 0))65 66INF = 10**186768dist = [INF] * total_nodes69 7071start_node = offset[0] + maps[0][0]72dist[start_node] = 073 7475heap = []76heapq.heappush(heap, (0, start_node))77 7879while heap:80 d, u = heapq.heappop(heap)81 if d != dist[u]:82 continue83 for v, cost in graph[u]:84 nd = d + cost85 if nd < dist[v]:86 dist[v] = nd87 heapq.heappush(heap, (nd, v))88 8990ans = INF91base = offset[N-1]92for j in range(len(levels[N-1])):93 node = base + j94 if dist[node] < ans:95 ans = dist[node]96 97print(ans)98