Advertisement
kosievdmerwe

Untitled

Sep 12th, 2021
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.13 KB | None | 0 0
  1. INF = float('inf')
  2.  
  3. class Solution:
  4.     def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:
  5.         eg = defaultdict(list)
  6.         for u, v, c in edges:
  7.             eg[u].append((v, c))
  8.             eg[v].append((u, c))
  9.         distance = [INF] * n
  10.         distance[0] = 0
  11.        
  12.         q = [(0, 0)]  # distance, node
  13.         while q:
  14.             cur_dist, cur_node = heappop(q)
  15.             if cur_dist > distance[cur_node]:
  16.                 continue
  17.             for neigh_node, edge_cnt in eg[cur_node]:
  18.                 neigh_dist = cur_dist + (edge_cnt + 1)
  19.                 if not (neigh_dist < distance[neigh_node]):
  20.                     continue
  21.                 distance[neigh_node] = neigh_dist
  22.                 heappush(q, (neigh_dist, neigh_node))
  23.        
  24.         ans = 0
  25.         for i in range(n):
  26.             if distance[i] <= maxMoves:
  27.                 ans += 1
  28.                
  29.         for u, v, c in edges:
  30.             from_u = max(0, maxMoves - distance[u])
  31.             from_v = max(0, maxMoves - distance[v])
  32.             ans += min(c, from_u + from_v)
  33.        
  34.         return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement