Why this algorithm fails for some of the test case from heapq import heappush, heappop…
- User
Why this algorithm fails for some of the test case from heapq import heappush, heappop def solve(): n, m, h = map(int, input().split()) horses = set(list(map(int, input().split()))) edges = [list(map(int, input().split())) for _ in range(m)]
adj = [[] for _ in range(n+1)] for u, v, w in edges: adj[u].append((v, w)) adj[v].append((u, w))
shortest = [[float('inf')] * 2 for _ in range(n + 1)] # 0 for R and 1 for M
def dijkstra(start, who):
codeshortest[start][who] = 0 no_horse, with_horse = set(), set() # track nodes that have been visited with/without horse if start in horses: with_horse.add(start) queue = [(0, start, 1)] else: no_horse.add(start) queue = [(0, start, 0)] while queue: dist, node, horse = heappop(queue) for neigh, weight in adj[node]: if not horse: if neigh in horses: if dist + weight > shortest[neigh][who] and neigh in with_horse: continue if dist + weight <= shortest[neigh][who]: shortest[neigh][who] = dist + weight else: with_horse.add(neigh) heappush(queue, (dist + weight, neigh, 1)) else: if dist + weight > shortest[neigh][who] and neigh in no_horse: continue if dist + weight <= shortest[neigh][who]: shortest[neigh][who] = dist + weight else: no_horse.add(neigh) heappush(queue, (dist + weight, neigh, 0)) else: if dist + weight // 2 > shortest[neigh][who] and neigh in with_horse: continue if dist + weight // 2 <= shortest[neigh][who]: shortest[neigh][who] = dist + weight // 2 else: with_horse.add(neigh) heappush(queue, (dist + weight // 2, neigh, 1))dijkstra(1, 0) dijkstra(n, 1) res = float('inf') for i in range(1, n + 1): res = min(res, max(shortest[i][0], shortest[i][1]))
- Assistant