|
| 1 | +Let us suppose the largest element now is X and that the second largest is Y. |
| 2 | + |
| 3 | +Suppose Frequency[X] = d |
| 4 | +We will Choose integers in the following way |
| 5 | + |
| 6 | +X, X, X, ... X (d times) |
| 7 | +X - 1, X - 1, ... X - 1 (d times) |
| 8 | +X - 2, X - 2, ... X - 2 (d times) |
| 9 | + |
| 10 | +So, we will choose the largest element at each step and we have d copies of it. |
| 11 | +This changes once X = Y |
| 12 | + |
| 13 | +----- |
| 14 | + |
| 15 | +Case 1 - K >= d(X - Y) |
| 16 | + |
| 17 | +In this case, we will sum the entire range |
| 18 | + |
| 19 | +Score += d*Sum(Y + 1, X) |
| 20 | +K -= d(X - Y) |
| 21 | + |
| 22 | +Frequency[Y] += X |
| 23 | + |
| 24 | +----- |
| 25 | + |
| 26 | +Case 2 - K < d(X - Y) |
| 27 | + |
| 28 | +We will take d copies of the largest element, as many times as we can and then take (K mod d) copies. |
| 29 | + |
| 30 | +Suppose, K = Qd + R, by the division algorithm. |
| 31 | + |
| 32 | +If d = 10 and K = 55, |
| 33 | +55 = 5(10) + 5 |
| 34 | +Q = 5, R = 5 |
| 35 | + |
| 36 | +We wil do 5(X + (X - 1) + ... + (X - Q + 1)) and then R copies of (X - Q) |
| 37 | + |
| 38 | +Overall, we will take |
| 39 | + |
| 40 | +Score += d*Sum(X - Q + 1, X) + R*(X - Q) |
| 41 | +K -= (d*(X - Q) + R) => K = 0 |
| 42 | + |
| 43 | +----- |
| 44 | + |
| 45 | +long long sum(long long left, long long right) |
| 46 | +{ |
| 47 | + if(left == 0) |
| 48 | + { |
| 49 | + return (right*(right + 1))/2; |
| 50 | + } |
| 51 | + |
| 52 | + return sum(0, right) - sum(0, left - 1); |
| 53 | +} |
| 54 | + |
| 55 | +int main() |
| 56 | +{ |
| 57 | + long long no_of_elements, k; |
| 58 | + cin >> no_of_elements >> k; |
| 59 | + |
| 60 | + vector <long long> A(no_of_elements + 1); |
| 61 | + for(int i = 1; i <= no_of_elements; i++) |
| 62 | + { |
| 63 | + cin >> A[i]; |
| 64 | + } |
| 65 | + |
| 66 | + priority_queue <long long> Q; |
| 67 | + Q.push(0); |
| 68 | + map <int, long long> frequency; |
| 69 | + for(int i = 1; i <= no_of_elements; i++) |
| 70 | + { |
| 71 | + frequency[A[i]]++; |
| 72 | + |
| 73 | + if(frequency[A[i]] == 1) |
| 74 | + { |
| 75 | + Q.push(A[i]); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + long long score = 0; |
| 80 | + while(Q.top() > 0 && k > 0) |
| 81 | + { |
| 82 | + long long x = Q.top(); |
| 83 | + Q.pop(); |
| 84 | + |
| 85 | + long long next = Q.top(); |
| 86 | + |
| 87 | + if(k >= frequency[x]*(x - next) ) |
| 88 | + { |
| 89 | + score += frequency[x]*sum(next + 1, x); |
| 90 | + frequency[next] += frequency[x]; |
| 91 | + |
| 92 | + k -= frequency[x]*(x - next); |
| 93 | + } |
| 94 | + else |
| 95 | + { |
| 96 | + long long quotient = k/frequency[x], remainder = k%frequency[x]; |
| 97 | + |
| 98 | + score += frequency[x]*(sum(x - quotient + 1, x)); |
| 99 | + score += remainder*(x - quotient); |
| 100 | + |
| 101 | + k = 0; |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + cout << score << "\n"; |
| 106 | + return 0; |
| 107 | +} |
0 commit comments