Editorial for COCI '14 Contest 1 #5 Zabava
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 numbers: the number of students moving per building.
Let us observe a building and assume that it will be emptied exactly times and see how it should be emptied optimally. Let us assume that the first time we emptied it was after students moved in it, the second time after a new students moved in it, and so on until the final time we emptied it after students, after which an additional students moved into it until the end.
The noise level before the first time it was emptied is , 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:
If we discard the division by two, this noise level is simply equal to the sum of squares plus the regular sum , 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 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 or . 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 marks the least possible noise level we can achieve in the first buildings with times of emptying it, that value is calculated so that we try every possible way of emptying the building (let's call it ) and check whether the given noise level, which is:
solution for the building with times of being emptied, as described above
is the minimal noise level so far. The final solution is, of course, . The complexity of this algorithm is .
Comments