Minimum Weighted Subgraph With the Required Paths II - Problem
You are given an undirected weighted tree with n nodes, numbered from 0 to n - 1. It is represented by a 2D integer array edges of length n - 1, where edges[i] = [ui, vi, wi] indicates that there is an edge between nodes ui and vi with weight wi.
Additionally, you are given a 2D integer array queries, where queries[j] = [src1j, src2j, destj].
Return an array answer of length equal to queries.length, where answer[j] is the minimum total weight of a subtree such that it is possible to reach destj from both src1j and src2j using edges in this subtree.
A subtree here is any connected subset of nodes and edges of the original tree forming a valid tree.
Input & Output
Example 1 — Basic Tree Query
$
Input:
edges = [[0,1,1],[1,2,1],[2,3,2]], queries = [[0,3,2]]
›
Output:
[4]
💡 Note:
To connect nodes 0 and 3 to destination 2, we need the path 0→1→2 (weight 2) and path 3→2 (weight 2). Total minimum weight is 4.
Example 2 — Multiple Queries
$
Input:
edges = [[0,1,1],[1,2,2],[1,3,3]], queries = [[0,2,3],[2,3,1]]
›
Output:
[6,5]
💡 Note:
Query 1: Connect 0,2 to 3 via node 1, weight = 1+2+3 = 6. Query 2: Connect 2,3 to 1, weight = 2+3 = 5.
Example 3 — Same Source and Destination
$
Input:
edges = [[0,1,1],[1,2,1]], queries = [[0,0,1]]
›
Output:
[1]
💡 Note:
Both sources are node 0, destination is 1. Only need path 0→1 with weight 1.
Constraints
- 1 ≤ n ≤ 104
- edges.length == n - 1
- 0 ≤ ui, vi ≤ n - 1
- 1 ≤ wi ≤ 106
- 1 ≤ queries.length ≤ 104
- 0 ≤ src1j, src2j, destj ≤ n - 1
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code