Editorial for COI '07 #2 Kolekcija
Submitting an official solution before solving the problem yourself is a bannable offence.
Notice first that the order of songs Igor wants to listen to is irrelevant (except for output order) so we can sort the input songs. Obviously, the songs displayed on screen will only change forward.
Suppose that the first songs in the sorted list have already been played. Let be the index of the first songs not on screen. This means that the list doesn't need to change while playing songs to . It can be proven that there exists an optimal sequence in which song is either on top or on the bottom of the screen while playing.
Using the previous claim we construct a recursive algorithm rec(A, isontop)
that calculates how many files still need to be read if the first songs in the sorted list have been played, and with the variable isontop
telling us if was on top or on the bottom of the list while playing.
rec( int A, bool isontop )
If isontop is true:
B = index of the first song not on screen while A is on top
last = x[A] + K-1
else:
B = A+1
last = x[A]
If B > M then return 0
return min{ K + rec( B, false ), x[B] - last + rec( B, true ) }
For the algorithm to be efficient, memoization is needed and we need to calculate in one preprocessing pass for each song the first song off the screen when is on top.
Comments