Editorial for COI '07 #2 Kolekcija


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.

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 A songs in the sorted list have already been played. Let B be the index of the first songs not on screen. This means that the list doesn't need to change while playing songs A+1 to B-1. It can be proven that there exists an optimal sequence in which song B 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 A songs in the sorted list have been played, and with the variable isontop telling us if A 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 A the first song off the screen when A is on top.


Comments

There are no comments at the moment.