Median Heap
시간 제한4초메모리 제한2048 MB
값과 변경 비용이 주어진 힙 모양 이진 트리에서, 주어진 중간값 교환 알고리즘이 루트에 목표값을 내놓도록 만드는 최소 총비용을 각 질의마다 구한다.
문제
Farmer John has a binary tree with nodes where the nodes are numbered from to ( and is odd). For , the parent of node is . Each node has an initial integer value , and a cost to change the initial value to any other integer value ().
He has been tasked by the Federal Bovine Intermediary (FBI) with finding an approximate median value within this tree, and has devised a clever algorithm to do so.
He starts at the last node and works his way backward. At every step of the algorithm, if a node would not be the median of it and its two children, he swaps the values of the current node and the child value that would be the median. At the end of this algorithm, the value at node (the root) is the median approximation.
The FBI has also given Farmer John a list of independent queries each specified by a target value (). For each query, FJ will first change some of the node's initial values, and then execute the median approximation algorithm. For each query, determine the minimum possible total cost for FJ to make the output of the algorithm equal to .
입력
The first line of input contains .
The next lines each contain two integers and .
The next line contains .
The next lines each contain a target value .
출력
Output lines, the minimum possible total cost for each target value .