Median Heap
Time limit4sMemory limit2048 MB
Given a binary tree with node values and change costs, find the minimum cost to make the median-swap process output each query value m at the root.
- Level
Hard9 of 10
- Topics
- Tree, Dynamic programming, Heap
- Solved
- No attempts yet
Problem
Farmer John has a binary tree with nodes, numbered from to (, and is odd). For , the parent of node is . Each node has an initial integer value and a cost to change it to any other integer value ().
The Federal Bovine Intermediary (FBI) asked Farmer John to find an approximate median value in this tree. He devised an algorithm for it.
He starts at the last node and works backward. At each step, if a node would not be the median of itself and its two children, he swaps the node's value with the child value that would be the median. When the algorithm ends, the value at the root (node ) is the approximate median.
The FBI also gave him independent queries (), each with a target value (). For each query, Farmer John first changes some of the initial values, then runs the algorithm. For each query, find the minimum total cost needed to make the algorithm's output equal .
Input
The first line contains .
The next lines each contain two integers and .
The next line contains .
The next lines each contain a target value .
Output
Output lines. Each line contains the minimum total cost for the corresponding target value .