Map
Time limit3sMemory limit128 MB
Partition n populations into m groups to minimize the sum over each group of |value - group median|, where the median can be any value meeting the half-half condition.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Sorting, Greedy, Prefix sum
- Solved
- No attempts yet
Problem
After redrawing the administrative divisions of Byteland, the cartographic office is preparing a new demographic map of the country. For technical reasons only a limited number of colors is available. The map must be colored so that regions with the same or similar population (number of inhabitants) receive the same color.
For a given color , let be a value such that:
- at least half of the regions colored have population not greater than , and
- at least half of the regions colored have population not less than .
In other words, is a median of the populations of the regions colored .
The coloring error of a region colored is , where is that region's population. The cumulative error is the sum of the coloring errors of all regions. We are looking for an optimal coloring, that is, one with the minimum cumulative error.
Write a program that reads the populations of the regions of Byteland, computes the minimum cumulative error, and writes the result to standard output.
Input
The first line contains an integer , the number of regions of Byteland, with .
The second line contains an integer , the number of colors used to color the map, with .
Each of the next lines contains one non-negative integer, the population of one region. No population exceeds .
Output
Output a single line containing one integer: the minimum cumulative error that can be achieved by an optimal coloring.