Ternary search

Building Construction

Given n buildings of height h1, h2, h3, ..., hn, the objective is to make every building has equal height. This can be done by removing bricks from a building or adding some bricks to a building. Removing a brick or adding a brick is done at certain cost which will be given along with the heights of the buildings. Find the minimal cost at which you can make the buildings look beautiful by reconstructing the buildings such that the n buildings satisfy h1 = h2 = h3 = ... = hn = k (k can be any number).

For convenience, all buildings are considered to be vertical piles of bricks, which are of same dimensions.


The first line contains number of buildings n (n105). The second line contains n integers which denotes the heights of the buildings h1, h2, h3, ..., hn (0hi10000). The third line contains n integers c1, c2, c3, ..., cn (0ci10000) which denotes the cost of adding or removing one unit of brick from the corresponding building.


Print the minimal cost to make all the buildings look beautiful.

Time limit 1 second
Memory limit 128 MiB
Input example #1
2 3 1 4
10 20 30 40
Output example #1
Input example #2
1 2 3
10 100 1000
Output example #2
Author Michael Medvediev