You are given an undirected graph (the "original graph") with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.

The graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there is an edge between nodes ui and vi in the original graph, and cnti is the total number of new nodes that you will subdivide the edge into. Note that cnti == 0 means you will not subdivide the edge.

To subdivide the edge [ui, vi], replace it with (cnti + 1) new edges and cnti new nodes. The new nodes are x1, x2, ..., xcnti, and the new edges are [ui, x1], [x1, x2], [x2, x3], ..., [xcnti-1, xcnti], [xcnti, vi].

In this new graph, you want to know how many nodes are reachable from the node 0, where a node is reachable if the distance is maxMoves or less.

Given the original graph and maxMoves, return the number of nodes that are reachable from node 0 in the new graph.

&nbsp;
Example 1:

Input: edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3
Output: 13
Explanation: The edge subdivisions are shown in the image above.
The nodes that are reachable are highlighted in yellow.


Example 2:

Input: edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4
Output: 23


Example 3:

Input: edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5
Output: 1
Explanation: Node 0 is disconnected from the rest of the graph, so only node 0 is reachable.


&nbsp;
Constraints:


	0 &lt;= edges.length &lt;= min(n * (n - 1) / 2, 104)
	edges[i].length == 3
	0 &lt;= ui &lt; vi &lt; n
	There are no multiple edges in the graph.
	0 &lt;= cnti &lt;= 104
	0 &lt;= maxMoves &lt;= 109
	1 &lt;= n &lt;= 3000


class Solution:
    def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:
        m = defaultdict(list)
        for a, b, p in edges:
            m[a].append((p, b))
            m[b].append((p, a))

        vis = set()
        queue = []
        heappush(queue, (0, 0))
        edgevis = set()
        edgeofl = defaultdict(lambda: 0)
        ans = 0
        while queue:
            # print(queue)
            cost, cur = heappop(queue)
            vis.add(cur)
            for p, nxt in m[cur]:
                if p < maxMoves - cost:
                    if (cur, nxt) not in edgevis and (nxt, cur) not in edgevis:
                        ans += p
                        # if nxt in vis:
                        # ans -= 1
                        edgevis.add((cur, nxt))
                        edgevis.add((nxt, cur))
                        if nxt not in vis:
                            heappush(queue, (cost + p + 1, nxt))
                else:
                    bal = maxMoves - cost
                    if (cur, nxt) in edgevis:
                        continue
                    if bal <= edgeofl[(cur, nxt)]:
                        continue
                    if bal + edgeofl[(nxt, cur)] < p:
                        ans += bal - edgeofl[(cur, nxt)]
                        edgeofl[(cur, nxt)] = bal
                    else:
                        ans += p - edgeofl[(nxt, cur)] - edgeofl[(cur, nxt)]
                        edgevis.add((cur, nxt))
                        edgevis.add((nxt, cur))
        return ans + len(vis)
class Solution {
    public int reachableNodes(int[][] edges, int maxMoves, int n) {
        int[][] graph = new int[n][n];
        for ( int[] t: graph ) {
            Arrays.fill(t, -1);
        }
        for ( int[] t: edges ) {
            graph[t[0]][t[1]] = t[2];
            graph[t[1]][t[0]] = t[2];
        }
        PriorityQueue<int[]> heap = new PriorityQueue<>( (a, b) -> b[1]-a[1] );
        int ans = 0;
        boolean[] vis = new boolean[n];
        heap.offer(new int[]{0, maxMoves});
        while ( !heap.isEmpty() ) {
            int[] info = heap.poll();
            int nearestNodeId = info[0];
            int maxMovesRemaining = info[1];
            if ( vis[nearestNodeId] ) {
                continue;
            }
            // visiting the current node
            vis[nearestNodeId] = true;
            // since we visited this node we increment our counter
            ans++;
            for ( int i=0; i<n; i++ ) {
                // checking if we do have an edge
                if ( graph[nearestNodeId][i]!=-1 ) {
                    if ( !vis[i] && maxMovesRemaining>=graph[nearestNodeId][i]+1 ) {
                        heap.offer( new int[] {i, maxMovesRemaining-graph[nearestNodeId][i]-1} );
                    }
                    int movesTaken = Math.min(maxMovesRemaining, graph[nearestNodeId][i]);
                    graph[nearestNodeId][i] -= movesTaken;
                    graph[i][nearestNodeId] -= movesTaken;
                    ans += movesTaken;
                }
            }
        }
        return ans;
    }
}
  class Solution {
  public:
  int reachableNodes(vector<vector<int>>& edges, int maxMoves, int n) {
  const int INF = 1e8;
  vector<vector<pair<int,int>> g(n);
  for(auto i: edges){
  g[i[0]].push_back({i[1],i[2]});
  g[i[1]].push_back({i[0],i[2]});
  }
  
  priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>> > pq;
  pq.push({0, 0}); //distance,node
  vector<int> d(n, INF);
  d[0] = 0;
  
  while(!pq.empty()){
       int dist = pq.top().first;
       int node = pq.top().second;
       pq.pop();
       //if(d[u.second]!=u.first) continue;
       for(auto it:g[node]){
           if(d[it.first]>dist+it.second+1)  //since number of edges=nodes in between+1
           {
               d[it.first]=dist+it.second+1;
               pq.push({d[it.first], it.first});
           }
       }
  }
  //now we have minimum distances to reach each node, so check how many reachable with minMoves
  int ans = 0;
  for(int i = 0; i < n; ++i) { // add 1 for nodes that can be visited
      if(d[i] <= maxMoves) 
        ans++;   
   } 
  

  /*
  Now add for intermediate newly added nodes
  Eg. 0->1 and 10 in between

  Visitable from 0 -> maxMoves-(dist/moves already covered by 0 (from source)) 
  Visitable from 1 -> maxMoves-(dist/moves already covered by 1 (from source))
  
  To calculate Extra nodes I can visit we follow above
  */
  for(auto i : edges) {
      int src=i[0],dest=i[1], between=i[2];
      int x = max(0, (maxMoves - d[src])); // nodes visited using edge e[0]->e[1]
      int y = max(0, (maxMoves - d[dest])); // nodes visited using edge e[1]->e[0]
      ans += min(between, x + y); //minimum to avoid overlapping in counting
  }
  return ans;
var reachableNodes = function(edges, maxMoves, n) {
    const g = Array.from({length: n}, () => []);
    
    for(let [u, v, cnt] of edges) {
        g[u].push([v, cnt + 1]);
        g[v].push([u, cnt + 1]);
    }
    
    // find min budget to reach from 0 to all nodes
    const budget = new Array(n).fill(Infinity);
    budget[0] = 0;
    const dijkstra = () => {
        // heap will be collection [node, weight]
        const heap = new MinPriorityQueue({ priority: (x) => x[1] });
        heap.enqueue([0, 0]);
        while(heap.size()) {
            const [n, c] = heap.dequeue().element;
            for(let [nextNode, cost] of g[n]) {
                let temp = c + cost;
                if(budget[nextNode] > temp) {
                    budget[nextNode] = temp;
                    heap.enqueue([nextNode, temp]);
                }
            }
        }
    };
    dijkstra();
    
    // add to sum all reachable nodes from 0 with max move
    let vis = 0;
    for(let w of budget) vis += w <= maxMoves;

    // add intermediate nodes between edges with available budget
    for(let [a, b, c] of edges) {
        let [availableFromA, availableFromB] = [maxMoves - budget[a], maxMoves - budget[b]];
        if(availableFromA < 0 || availableFromB < 0) {
            vis += Math.max(availableFromA, 0) + Math.max(availableFromB, 0);
        } else {
            const total = availableFromA + availableFromB;
            vis += total - Math.max(total - c, 0);
        }
    }
    
    return vis;
};
Reachable Nodes In Subdivided Graph