Problem Description
Given an undirected tree with n nodes (indexed 0 to n-1) and n-1 edges, each node has a given price. You are also provided several trips defined by their start and end nodes. You can choose a set of non-adjacent nodes (before making any trip) and halve their price. The cost of a trip is the sum of the prices on the path taken. The goal is to pick the nodes to discount so that the total cost of all trips is minimized.
Key Insights
- Count the number of times each node is used on any trip. As the tree is undirected and unique paths exist between any two nodes, a DFS/BFS can be used per trip.
- Convert the problem into one of maximizing the savings: For a node, if its cost is halved, the saving is half of its price multiplied by the number of times it appears. The total trip cost becomes (total cost without discounts) minus the total “saving.”
- Because one can only discount non-adjacent nodes, the problem reduces to a tree dynamic programming (DP) formulation on the tree with two states per node: discounted (chosen) or not.
- Use a DFS-based DP on the tree (rooting the tree arbitrarily) where: • If a node is discounted, its children cannot be discounted. • Otherwise, each child may be either discounted or not based on which yields maximum saving.
- Final answer = total trip cost without discount − maximum total saving calculated by the DP.
Space and Time Complexity
Time Complexity: O(t * n + n), where t is the number of trips (since each trip may require a DFS to record the unique path) and n is the number of nodes (for the DP traversal).
Space Complexity: O(n + t) due to storing the tree adjacency list, count array, and recursion stack.
Solution
The solution first records how many times each node is visited by processing each trip with a DFS that finds the unique path from start to end. Once the frequency counts are available, the “saving” for discounting a node is count[node]*(price[node]//2). Next, an arbitrary root is chosen to run a DFS-based tree DP where for each node, two values are computed:
- savings if the node is not discounted: sum of maximum savings obtainable by children (they may or may not be discounted).
- savings if the node is discounted: saving from the current node plus savings from children when none of them is discounted. Finally, subtract the maximum saving (obtained from the root’s DP) from the total cost (computed with the original prices and counts) to get the minimized cost.