Editorial for COCI '14 Contest 1 #5 Zabava


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Firstly, we need to notice that the sequence of students moving into the buildings is irrelevant: all that matters is how many students move into an individual building, because the parties in a certain building happen completely independently of other buildings. Therefore, we can assume that we are given M numbers: the number of students moving per building.

Let us observe a building and assume that it will be emptied exactly P times and see how it should be emptied optimally. Let us assume that the first time we emptied it was after x_1 students moved in it, the second time after a new x_2 students moved in it, and so on until the final time we emptied it after x_P students, after which an additional x_{P+1} students moved into it until the end.

The noise level before the first time it was emptied is 1+2+\dots+x_1 = \frac{x_1(x_1+1)}{2}, and the analogous formula holds for the noises after the first time it was emptied, the second time and all the rest until the end. The total noise level in a building is therefore:

\displaystyle \frac 1 2 \sum_{i=1}^{P+1} x_i(x_i+1)

If we discard the division by two, this noise level is simply equal to the sum of squares x_i^2 plus the regular sum x_i, but that sum is constant and equal to the total number of students who moved into that building. So, we need to minimize the sum of squares of P+1 numbers, and the sum of these numbers is given.

From the arithmetic and quadratic mean inequality, it holds that the sum of squares is minimal when the numbers are equal. Here, it is occasionally impossible to achieve because of (in)divisibility, but the numbers will be "almost equal", in other words, they will differ from one another only by 0 or 1. This division and the required sum can be easily calculated in constant time by using simple formulas. This is an effective way of solving the problem for one building and a fixed number of times that building is emptied.

Now the task can be solved by dynamic programming. If dp(m, k) marks the least possible noise level we can achieve in the first m buildings with k times of emptying it, that value is calculated so that we try every possible way of emptying the m^\text{th} building (let's call it P) and check whether the given noise level, which is:

dp(m-1, k-P) + (solution for the m^\text{th} building with P times of being emptied, as described above)

is the minimal noise level so far. The final solution is, of course, dp(M, K). The complexity of this algorithm is \mathcal O(MK^2).


Comments

There are no comments at the moment.