Imagine you're a network engineer tasked with optimizing data transmission paths in a tree-structured network. You have an undirected tree with n nodes labeled from 0 to n-1, where each edge has a specific weight representing transmission cost.
Given the tree structure through edges[i] = [ui, vi, wi] (indicating an edge between nodes ui and vi with weight wi), you need to answer multiple queries about path optimization.
For each query [ai, bi], you must find the minimum number of edge weight modifications needed to make all edges on the path from node ai to node bi have the same weight. You can change any edge's weight to any value in one operation.
Key Points:
- Each query is independent - the tree resets after each query
- The path between any two nodes in a tree is unique
- You want to minimize operations, so keep the most frequent weight unchanged
Input & Output
Visualization
Time & Space Complexity
O(n log n) for preprocessing binary lifting, O(log n) per query for LCA
Space for binary lifting table and weight frequency arrays at each level
Constraints
- 1 โค n โค 104
- edges.length == n - 1
- edges[i].length == 3
- 0 โค ui, vi โค n - 1
- 1 โค wi โค 26
- 1 โค queries.length โค 2 * 104
- queries[i].length == 2
- 0 โค ai, bi โค n - 1