Problem Description
Given an undirected graph where each edge [u, v, cnt] is subdivided into (cnt + 1) segments by inserting cnt new nodes along the edge, determine how many nodes in the resulting graph are reachable from node 0 using at most maxMoves moves. A move traverses one edge in the subdivided graph.
Key Insights
- Instead of explicitly constructing the subdivided graph (which could be huge), use a modified graph algorithm on the original graph.
- Use Dijkstra’s algorithm to compute the minimum number of moves required to reach each original node from node 0.
- For each edge, determine how many of the subdivided nodes can be reached from either end based on the remaining moves.
- For each edge between u and v with cnt subdivided nodes, the count of reachable new nodes is min(cnt, max(0, maxMoves - dist[u]) + max(0, maxMoves - dist[v])).
Space and Time Complexity
Time Complexity: O(E log N) where E is the number of edges and N is the number of original nodes. Space Complexity: O(N + E) for storing the graph and distance array.
Solution
We solve the problem by using Dijkstra’s algorithm on the original graph where the weight to traverse an edge [u, v, cnt] is (cnt + 1). This yields the minimum moves required to reach each original node. Once we have these distances:
- Count each original node for which the distance is within maxMoves.
- For every subdivided edge, compute the available moves remaining from both endpoints.
- The number of reachable subdivided nodes on an edge is the minimum between cnt and the sum of moves remaining from both endpoints. By summing these counts, we obtain the total number of reachable nodes in the subdivided graph.