Shortest Path in a Weighted Tree Problem
Description
LeetCode Problem 3515.
You are given an integer n and an undirected, weighted tree rooted at node 1 with n nodes numbered from 1 to n. This is represented by a 2D array edges of length n - 1, where edges[i] = [u_i, v_i, w_i] indicates an undirected edge from node u_i to v_i with weight w_i.
You are also given a 2D integer array queries of length q, where each queries[i] is either:
[1, u, v, w']– Update the weight of the edge between nodesuandvtow', where(u, v)is guaranteed to be an edge present inedges.[2, x]– Compute the shortest path distance from the root node 1 to nodex.
Return an integer array answer, where answer[i] is the shortest path distance from node 1 to x for the i^th query of [2, x].
Example 1:
Input: n = 2, edges = [[1,2,7]], queries = [[2,2],[1,1,2,4],[2,2]]
Output: [7,4]
Explanation:

- Query [2, 2]: The shortest path from root node 1 to node 2 is 7.
- Query [1, 1, 2, 4]: The weight of edge (1, 2) changes from 7 to 4.
- Query [2, 2]: The shortest path from root node 1 to node 2 is 4.
Example 2:
Input: n = 3, edges = [[1,2,2],[1,3,4]], queries = [[2,1],[2,3],[1,1,3,7],[2,2],[2,3]]
Output: [0,4,2,7]
Explanation:

- Query [2, 1]: The shortest path from root node 1 to node 1 is 0.
- Query [2, 3]: The shortest path from root node 1 to node 3 is 4.
- Query [1, 1, 3, 7]: The weight of edge (1, 3) changes from 4 to 7.
- Query [2, 2]: The shortest path from root node 1 to node 2 is 2.
- Query [2, 3]: The shortest path from root node 1 to node 3 is 7.
Example 3:
Input: n = 4, edges = [[1,2,2],[2,3,1],[3,4,5]], queries = [[2,4],[2,3],[1,2,3,3],[2,2],[2,3]]
Output: [8,3,2,5]
Explanation:

- Query [2, 4]: The shortest path from root node 1 to node 4 consists of edges (1, 2), (2, 3), and (3, 4) with weights 2 + 1 + 5 = 8.
- Query [2, 3]: The shortest path from root node 1 to node 3 consists of edges (1, 2) and (2, 3) with weights 2 + 1 = 3.
- Query [1, 2, 3, 3]: The weight of edge (2, 3) changes from 1 to 3.
- Query [2, 2]: The shortest path from root node 1 to node 2 is 2.
- Query [2, 3]: The shortest path from root node 1 to node 3 consists of edges (1, 2) and (2, 3) with updated weights 2 + 3 = 5.
Constraints:
1 <= n <= 10^5edges.length == n - 1edges[i] == [u_i, v_i, w_i]1 <= u_i, v_i <= n1 <= w_i <= 10^4- The input is generated such that
edgesrepresents a valid tree. 1 <= queries.length == q <= 10^5queries[i].length == 2or4queries[i] == [1, u, v, w']or,queries[i] == [2, x]1 <= u, v, x <= n(u, v)is always an edge fromedges.1 <= w' <= 10^4
Solution
Approach: Euler Tour and Fenwick Tree
In a tree the path from the root to a node is unique, so the distance of x is the sum of the edge weights on that path. Recomputing it for every query is too slow, but an edge update only changes the distance of every node in the subtree below that edge.
Number the nodes in preorder (with an iterative DFS to avoid deep recursion), so each subtree is a contiguous range [tin, tin + size - 1]. Keep a Fenwick tree over a difference array that supports adding a value to a range and reading a single position:
- Initially, add the weight of the edge above each node
vto the range ofv's subtree. - For an update
[1, u, v, w], the child endpoint is whichever ofu,vhas the other as its parent. Addw - oldWeightto the child's subtree range and rememberw. - For a query
[2, x], the answer is the value stored attin[x].
Complexity: O((n + q) log n) time and O(n) extra space.
class Solution:
def treeQueries(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]:
g = [[] for _ in range(n + 1)]
for u, v, w in edges:
g[u].append((v, w))
g[v].append((u, w))
# Preorder numbering: the subtree of x is the range [tin[x], tin[x] + size[x] - 1].
tin = [0] * (n + 1)
size = [1] * (n + 1)
parent = [0] * (n + 1)
wt = [0] * (n + 1) # weight of the edge to the parent
order = []
stack = [1]
while stack:
x = stack.pop()
tin[x] = len(order) + 1
order.append(x)
for y, w in g[x]:
if y != parent[x]:
parent[y] = x
wt[y] = w
stack.append(y)
for x in reversed(order):
if parent[x]:
size[parent[x]] += size[x]
# Fenwick tree over difference array: range add, point query.
tree = [0] * (n + 2)
def add(i: int, d: int) -> None:
while i <= n + 1:
tree[i] += d
i += i & -i
def range_add(l: int, r: int, d: int) -> None:
add(l, d)
add(r + 1, -d)
def point(i: int) -> int:
s = 0
while i > 0:
s += tree[i]
i -= i & -i
return s
for x in range(2, n + 1):
range_add(tin[x], tin[x] + size[x] - 1, wt[x])
ans = []
for q in queries:
if q[0] == 1:
u, v, w = q[1], q[2], q[3]
child = u if parent[u] == v else v
range_add(tin[child], tin[child] + size[child] - 1, w - wt[child])
wt[child] = w
else:
ans.append(point(tin[q[1]]))
return ans