Editorial for Baltic OI '09 P1 - Beetle


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.

We will assume that x1x2xsxn, this can be done in O(nlogn). Here, xs=0 is an extra added "start" drop we will find useful, and n is the total number of drops with this new drop included.

Suppose that the beetle drinks k drops at time moments t1,t2,,tk respectively. The total amount of water drunk will be (mt1)+(mt2)++(mtk)=km(t1+t2++tk). Since km is fixed for fixed k, we are to minimize the sum t1+t2++tk. Actually, this formula only holds if t1,t2,,tkm, because the beetle does not really get any "penalty points" for passing a drop that is no more. However, letting these penalty points will not change the maximal possible amount, as there is always an optimal route in which the beetle stops before t>m (and it is clever to do so!).

Also notice that the next drop the beetle will drink is always either the closest from left or from right, because there's no point in not drinking a drop if one is passing it anyway.

From here on we use dynamic programming. Let L(i,j,k) be the least possible "penalty sum" beetle would get if at time moment t=0 it started at xi and would drink exactly k drops, but there were no drops i,i+1,,j. Similarly, let R(i,j,k) be the least possible "penalty sum" for drinking k drops starting at xj if there were no drops i,i+1,,j.

If the beetle willing to drink k drops starts at xi and there are no drops i,i+1,,j, then it can either go for drop at xi1 or xj+1, which reduces the problem to either L(i1,j,k1) or R(i,j+1,k1). The penalty (time spent) for current drop will be either xixi1 or xj+1xi. In any case, this penalty will count in for all other k1 drops the beetle is going to drink. Therefore the following equations hold:

L(i,j,k)=min{L(i1,j,k1)+k(xixi1),R(i,j+1,k1)+k(xj+1xi)}R(i,j,k)=min{L(i1,j,k1)+k(xjxi1),R(i,j+1,k1)+k(xj+1xj)}

The boundary conditions are:

L(i,j,0)=R(i,j,0)=0,1ijn

Now we can check what is the maximal amount of water the beetle can drink if starts at time moment t=0 at xs and there is no drop s:

max{kmL(s,s,k):0k<n}

We find it by consequently calculating L and R values in O(n3) time and O(n2) memory.


Comments

There are no comments at the moment.