Gaurav's Coin Piles

0

0 votes
Mathematics, Hard
Problem

Gaurav has N piles of coins where each coin is of 1 unit. Piles are numbered from 1 to N. Each pile has a total value V[i]. It is assured that 0V[i]K, where 1iN and K is the maximum possible value of any pile can hold.

Gaurav can perform an operation zero or more times. In each operation, he chooses two piles A and B and shifts some coins from one pile to another until either the value of pile A reduces to zero or pile B's value becomes equal to K, whichever happens first.

Now after performing all the operations, if a pile, say P, has value X (where definitely 0XK), then he will gain a profit of profit[X] corresponding to pile P. This profit array will be given in standard input. Total profit obtained would be the summation of profits from all the piles.

Your task is to find the maximum profit Bob can gain.

Input Format:
First line contains integer T, the number of test cases.
For each test case, there will be 3 lines.
First line of each test cases contains two space separated integers N and K.
Second line contains N space separated integers denoting the array V, value of each pile.
Third line contains K+1 space separated integers denoting the array profit array from profit[0] to profit[K].

Output Format:
For each test case, you need to print one integer in a new line, the maximum profit Gaurav can gain.

Input Constraints:
1T5
1N15
1K50
0V[i]K, where 1iN
0profit[i]106, where 0iK

Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

The best way is to subtract 2 from first pile and add it to second pile. So now it becomes [0,5]. Total benefit for both piles is profit[0]+profit[5]=20+20=40.

Although, you would be getting more benefit, if you were allowed to partially move some part of first pile to second pile, But that is not allowed in operation. You had to transfer till one value reaches to zero or the other reaches to K, who ever reaches first.

Editor Image

?