Under construction

Still being built. Things may change

Median Heap

Time limit4sMemory limit2048 MB

Summary
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 NN nodes, numbered from 11 to NN (1≤N<2⋅1051 \leq N < 2\cdot 10^5, and NN is odd). For i>1i>1, the parent of node ii is ⌊i/2⌋\lfloor i/2\rfloor. Each node has an initial integer value aia_i and a cost cic_i to change it to any other integer value (0≤ai,ci≤1090\le a_i,c_i\le 10^9).

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 NN 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 11) is the approximate median.

The FBI also gave him QQ independent queries (1≤Q≤2⋅1051 \leq Q \leq 2\cdot 10^5), each with a target value mm (0≤m≤1090\le m\le 10^9). 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 mm.

Input

The first line contains NN.

The next NN lines each contain two integers aia_i and cic_i.

The next line contains QQ.

The next QQ lines each contain a target value mm.

Output

Output QQ lines. Each line contains the minimum total cost for the corresponding target value mm.

Examples1

  1. Example 1

    Input
    5
    10 10000
    30 1000
    20 100
    50 10
    40 1
    11
    55
    50
    45
    40
    35
    30
    25
    20
    15
    10
    5
    
    Expected output
    111
    101
    101
    100
    100
    100
    100
    0
    11
    11
    111