Editorial for COCI '07 Contest 6 #6 Cestarine
Submitting an official solution before solving the problem yourself is a bannable offence.
Let us first solve the problem without the constraint that a driver may not use his ticket at the same exit where the ticket was issued. Because the tickets may be exchanged arbitrarily, any driver can obtain any ticket. It is easy to see that the optimal solution is to sort the tickets, sort the drivers by their desired exits, and give the drivers tickets in order.
What if a driver gets a ticket issued at the same exit he needs to use? The best action would be for him to swap his ticket with one of his colleagues next to him in the sorted sequence, which is always possible. But what if, as in the second example test case, two drivers want to exchange tickets with the same driver? Then we need to allow them to exchange tickets not only with immediately adjacent drivers, but also those 2 indices away in the sorted sequence. From this analysis, we obtain a dynamic programming solution.
Let be the cost of the optimal distribution of tickets for all drivers up to driver (the drivers are sorted by their exits). Let be the cheapest distribution of tickets in positions to drivers in positions . There are possible distributions, but because will be at most , we can check each one and select the distribution which results in the least total cost. The DP relation is:
The solution is .
Comments