Official Analysis (C++, Java, Python)
Explanation
First, observe that the maximum possible amount of milk is generated by assigning the largest multipliers to the cows with the highest milk production values. This is achieved by sorting the array of milk production values in nondecreasing order.
Let's observe the effect of changing an element when maintaining sorted order and how this affects the value of the original value of . Suppose we consider a query that changes to . Let the positions of and in the sorted version of be and , respectively.
If we consider the sorted version of , then there are two cases:
- If , moves right and the indices are shifted left.
- If , moves left and the indices are shifted right.
For the first case, the multipliers of the elements shifted left decrease by 1, so decreases by the sum of those elements, which can be found using prefix sums. We also have to account for the contributions of the removal of the original element and addition of the new element — we can find their positions using binary search. The second case can be handled similarly.
Implementation
Time Complexity:
Python
import bisectn = int(input())a = [int(x) for x in input().split()]# Sorting and prefix sumssorted_a = sorted(a)p_sum = [0]for i in range(n):p_sum.append(p_sum[-1] + sorted_a[i])
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!