KOPC12A - K12 - 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 re-constructing 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. 

Input

The first line of input contains an integer T which denotes number of test cases .This will be followed by 3 * T lines, 3 lines per test case. The first line of each test case contains an integer n and the  second line contains n integers which denotes the heights of the buildings [h1, h2, h3 ... hn] and the third line contains n integers [c1, c2, c3 ... cn] which denotes the cost of adding or removing one unit of brick from the corresponding building.

T <= 15; n <= 10000; 0 <= Hi <= 10000; 0 <= Ci <= 10000;

Output

The output must contain T lines each line corresponding to a testcase.

Example

Input:
1
3
1 2 3
10 100 1000

Output:
120

Added by:Radhakrishnan Venkataramani
Date:2012-01-31
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64
Resource:Own

hide comments
2017-04-10 09:49:24
Can someone please tell me why can we apply ternary search here?
I thought that it could be applied only when the function is unimodal (i.e strictly decreasing reaches min and then strictly increasing or viceversa)
Thanks :)

Last edit: 2017-04-10 09:49:42
2016-07-17 23:17:42
There is 2 algorithm. one is O(nlogn) . other algorithm run O(10000) in worst case (without binary and ternary search)

Last edit: 2016-07-17 23:59:27
2016-03-16 08:12:57 SUBHAJIT GORAI
elegant O(n) solution ...no need of binary or ternary search
2016-03-03 21:21:35 Deepak
ternary search.. :)
2016-02-18 21:22:40 sharif ullah
re constructing !!!!!!!!!!!!!
so,
3
0 0 0
1 1 1
2015-08-24 00:43:42
two words: ternary search
2015-06-24 18:55:29 ANKIT TAPARIA
Easy using binary search!!!
2015-02-05 11:58:16 jonty007
2
3
0 0 0
1 1 1
3
0 0 1
1 1 1
output???

Last edit: 2015-02-05 11:58:57
2014-12-27 15:12:29 lucky
what is the order of this???
2014-10-20 21:09:59 Ayush Vatsa
learnt a lot....nice question

though test cases are weak

Last edit: 2014-10-21 06:09:40
© Spoj.com. All Rights Reserved. Spoj uses Sphere Engine™ © by Sphere Research Labs.