Minimize the Total Price of the Trips - Problem
You are given an undirected tree with n nodes indexed from 0 to n-1. The tree is represented by a 2D integer array edges of length n-1, where edges[i] = [ai, bi] indicates an edge between nodes ai and bi.
Each node has an associated price given by the integer array price, where price[i] is the price of the i-th node. The price sum of a path is the sum of prices of all nodes on that path.
You are given a 2D integer array trips, where trips[i] = [starti, endi] represents a trip from node starti to node endi. Before performing any trips, you can choose some non-adjacent nodes and halve their prices.
Return the minimum total price sum to perform all the given trips.
Input & Output
Example 1 — Basic Tree with Single Trip
$
Input:
n = 4, edges = [[0,1],[1,2],[1,3]], price = [2,2,10,6], trips = [[0,3]]
›
Output:
6
💡 Note:
Path from 0→3 is [0,1,3] with original cost 2+2+6=10. We can discount non-adjacent nodes 0 and 3 (prices 2→1 and 6→3), giving total cost 1+2+3=6.
Example 2 — Multiple Trips
$
Input:
n = 4, edges = [[0,1],[1,2],[1,3]], price = [2,2,10,6], trips = [[0,2],[1,3]]
›
Output:
16
💡 Note:
Trip 0→2 uses path [0,1,2], trip 1→3 uses path [1,3]. Node usage frequencies: node 0→1 time, node 1→2 times, node 2→1 time, node 3→1 time. Optimal discounting minimizes total cost to 16.
Example 3 — Linear Tree
$
Input:
n = 3, edges = [[0,1],[1,2]], price = [1,10,1], trips = [[0,2]]
›
Output:
7
💡 Note:
Path 0→2 is [0,1,2] with original cost 1+10+1=12. We can discount nodes 0 and 2 (non-adjacent), giving cost (1//2)+10+(1//2) = 0+10+0 = 10. Or discount just node 1: 1+(10//2)+1 = 1+5+1 = 7. Minimum is 7.
Constraints
- 1 ≤ n ≤ 50
- edges.length == n - 1
- 0 ≤ ai, bi ≤ n - 1
- edges represents a valid tree
- 1 ≤ price[i] ≤ 1000
- 1 ≤ trips.length ≤ 100
- 0 ≤ starti, endi ≤ n - 1
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code