Estimation
Time limit5sMemory limit128 MB
Partition an array into k contiguous sections, each replaced by one constant value, to minimize the total absolute error. Multiple test cases until 0 0.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Divide and conquer, Sorting, Prefix sum
- Solved
- No attempts yet
Problem
"There are too many numbers here!" your boss bellows. "How am I supposed to make sense of all of this? Pare it down! Estimate!"
You are disappointed, because it took a lot of work to generate those numbers, but you will do what your boss asks.
You decide to estimate as follows. You are given an array of numbers, and you partition it into contiguous sections that need not have the same size. Each section is then estimated by a single number. Formally, from the array of size you build another array of size that consists of contiguous sections: whenever indices and lie in the same section, . Your goal is to minimize the error, defined as the sum of the absolute differences .
Input
The input contains several test cases. Each test case starts with a line holding two integers () and ( and ), where is the size of the array and is the number of contiguous sections to use. Each of the next lines contains one integer of ; every element satisfies . The input ends with a line containing two zeros.
Output
For each test case, output a single line containing one integer: the minimum error you can achieve. Print no extra spaces, and do not separate answers with blank lines. Every answer fits in a signed 64-bit integer.