#K43857. Equalizing Tree Energies

    ID: 27402 Type: Default 1000ms 256MiB

Equalizing Tree Energies

Equalizing Tree Energies

You are given n trees, where the i-th tree has energy Ei. A spell cast can increase or decrease the energy of a tree by 1 unit. Your task is to determine the minimum total number of spell casts required to make all trees have the same energy level. It can be proved that choosing the median energy minimizes the total cost under the L1 norm, i.e., the answer is given by

spells=i=1nEim,\text{spells} = \sum_{i=1}^{n} |E_i - m|,

where \(m\) is the median of the energies. Note that if n is even, any value between the two middle values minimizes the sum, and you may use the upper median (i.e. the element at index \(\lfloor n/2 \rfloor\)) as the target energy.

inputFormat

The first line contains an integer n (1 ≤ n ≤ 105) — the number of trees.

The second line contains n space-separated integers E1, E2, ..., En (0 ≤ Ei ≤ 106) representing the energy of each tree.

outputFormat

Output a single integer — the minimum total number of spell casts required to equalize the energy levels of all trees.

## sample
4
2 3 5 5
5

</p>