Shortest Path in a Weighted Tree - Problem
Dynamic Tree Path Queries
You're managing a weighted tree network with
You need to handle two types of dynamic queries:
โข Type 1:
โข Type 2:
Goal: Return an array containing the shortest distances for all Type 2 queries, processed in order.
Since it's a tree, there's exactly one path between any two nodes, making each shortest path query deterministic but requiring efficient updates.
You're managing a weighted tree network with
n nodes numbered from 1 to n, rooted at node 1. The network is represented by an array edges where each edges[i] = [u_i, v_i, w_i] represents a bidirectional connection between nodes u_i and v_i with weight w_i.You need to handle two types of dynamic queries:
โข Type 1:
[1, u, v, w'] - Update the weight of edge between nodes u and v to w'โข Type 2:
[2, x] - Find the shortest path distance from root node 1 to node xGoal: Return an array containing the shortest distances for all Type 2 queries, processed in order.
Since it's a tree, there's exactly one path between any two nodes, making each shortest path query deterministic but requiring efficient updates.
Input & Output
example_1.py โ Basic Tree Operations
$
Input:
n = 4, edges = [[1,2,5], [2,3,2], [2,4,3]], queries = [[2,3], [1,2,3,6], [2,3], [2,4]]
โบ
Output:
[7, 8, 9]
๐ก Note:
Initial tree: 1--(5)--2--(2)--3, 2--(3)--4. Query path 1โ3: 5+2=7. Update edge (2,3) to weight 6. Query path 1โ3: 5+6=11. Query path 1โ4: 5+3=8.
example_2.py โ Multiple Updates
$
Input:
n = 3, edges = [[1,2,1], [2,3,2]], queries = [[2,3], [1,1,2,5], [2,3], [1,2,3,1], [2,3]]
โบ
Output:
[3, 7, 6]
๐ก Note:
Path 1โ3 initially costs 1+2=3. After updating (1,2) to 5: cost becomes 5+2=7. After updating (2,3) to 1: cost becomes 5+1=6.
example_3.py โ Single Node Query
$
Input:
n = 2, edges = [[1,2,10]], queries = [[2,1], [1,1,2,20], [2,1]]
โบ
Output:
[0, 0]
๐ก Note:
Querying distance from root (node 1) to itself always returns 0, regardless of edge weight updates.
Constraints
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code