#C5146. Equalizing Array to the Median

    ID: 48763 Type: Default 1000ms 256MiB

Equalizing Array to the Median

Equalizing Array to the Median

You are given T test cases. In each test case, an array of integers is provided. Your task is to compute the minimum total cost to make all elements in the array equal by only changing their values. The allowed operation is to increase or decrease an element, and the cost for each change is the absolute difference between the original and the target value.

The optimal strategy is to make every element equal to the median of the array. Mathematically, if the sorted array is \(a_0, a_1, \dots, a_{n-1}\), then the median \(m\) is defined as: \[ m = \begin{cases} a_{\lfloor n/2 \rfloor} & \text{if } n \text{ is odd},\\ a_{(n/2)-1} & \text{if } n \text{ is even}. \end{cases} \] The total cost is given by: \[ \text{Cost} = \sum_{i=0}^{n-1} |a_i - m|. \]

Compute and output the cost for each test case on a separate line.

inputFormat

The first line contains an integer T representing the number of test cases. Each test case consists of two lines:

  • The first line contains an integer n denoting the size of the array.
  • The second line contains n space-separated integers representing the elements of the array.

outputFormat

For each test case, print a single integer representing the minimum total cost to equalize the array elements to the median. The result for each test case should be printed on a new line.

## sample
3
3
1 2 3
4
1 10 2 9
5
3 3 1 2 1
2

16 4

</p>