Official Analysis (C++, Python)
Explanation
The problem asks us to minimize the sum of for all , using an of our choice, with each difference under modulo (strictly, optimizing the sum of ). Thus, let us first consider this problem without the modulus.
Letting be the median of those numbers minimizes the total distance. In the case that is even, any number between the two numbers in the middle (inclusive) would work.
We now consider the modulus. First, take each number modulo . Observe that any element can be the median if we add or subtract from some elements, shifting some values to the left and right of the element. For example, given and , we can make the median by adding to elements and , resulting in the array .
Thus, every element is a candidate for . We compute the cost for each after shifting, and take the best candidate, which is the that results in the smallest sum of absolute differences.
To implement this, we first sort . Then, we consider each element in a as a potential . For each candidate value, we compute either the number of elements before it that must be increased by or the number of elements after it that must be decreased by in order to make this value the median. After that, we use prefix sums to compute the total absolute difference. However, this requires us to access indices of that are not in the range; to mitigate this, we prepend to a copy of with subtracted from every element, and append a copy of with added to every element. The range in will then be the original elements we enumerate over, and we will be able to access the elements that come before or after the original array.
The final answer will be the smallest sum of absolute differences over all such indices.
Implementation
Time Complexity: per test case
t = int(input())for _ in range(t):n, m = map(int, input().split())nums = list(map(int, input().split()))# Mod, sort, and construct arrayrems = sorted([x % m for x in nums])# s is prepended/appended arrays = [x - m for x in rems] + rems + [x + m for x in rems]
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!