Table of Contents

ExplanationImplementation

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 TT. Suppose we consider a query that changes aia_i to vv. Let the positions of aia_i and vv in the sorted version of aa be xx and yy, respectively.

If we consider the sorted version of aa, then there are two cases:

  1. If vaiv \ge a_i, aia_i moves right and the indices x+1, x+2, , yx+1,\ x+2,\ \dots,\ y are shifted left.
  2. If v<aiv < a_i, aia_i moves left and the indices y, y+1, , xy,\ y+1,\ \dots,\ x are shifted right.

For the first case, the multipliers of the elements shifted left decrease by 1, so TT 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: O((N+Q)logN)\mathcal{O}((N + Q)\log N)

Python

import bisect
n = int(input())
a = [int(x) for x in input().split()]
# Sorting and prefix sums
sorted_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!