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:
11
💡 Note:
Path from 0→3 is [0,1,3]. Original cost: 2+2+6=10. We can discount node 0 (price 2→1) and node 3 (price 6→3, not adjacent to 0). Total: 1+2+3=6. Wait, let me recalculate: discount nodes 0 and 3 gives cost 1+2+3=6, but we need to check if this is optimal among all valid discount combinations.
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:
23
💡 Note:
Trip 0→2 uses path [0,1,2], trip 1→3 uses path [1,3]. Node usage: 0→1 time, 1→2 times, 2→1 time, 3→1 time. We can discount non-adjacent nodes optimally to minimize total cost.
Example 3 — Linear Tree
$
Input:
n = 3, edges = [[0,1],[1,2]], price = [1,10,1], trips = [[0,2]]
›
Output:
6
💡 Note:
Path 0→2 is [0,1,2]. Original cost: 1+10+1=12. We can discount nodes 0 and 2 (non-adjacent), giving cost: 0.5+10+0.5=11. But we can also discount just node 1 (middle node with highest price), giving cost: 1+5+1=7. Actually, discounting nodes 0 and 2 gives: 1+10+1=12, with discount: 0+10+0=10. Wait, integer division: (1//2)+(10)+(1//2) = 0+10+0 = 10. Hmm, let me recalculate properly.
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
Understanding the Visualization
1
Input Tree
Undirected tree with node prices and trip routes
2
Count Usage
Find how often each node is used across all trips
3
Apply Discounts
Choose non-adjacent nodes to discount optimally
4
Calculate Cost
Sum up total cost for all trips with discounts
Key Takeaway
🎯 Key Insight: Use tree DP to optimally place discounts on non-adjacent nodes based on usage frequency
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code