Editorial for COCI '07 Contest 6 #6 Cestarine


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.

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 dp[n] be the cost of the optimal distribution of tickets for all drivers up to driver n (the drivers are sorted by their exits). Let distribution(n, k) be the cheapest distribution of tickets in positions n, n-1, \dots, n-k to drivers in positions n, n-1, \dots, n-k. There are (k+1)! possible distributions, but because k will be at most 2, we can check each one and select the distribution which results in the least total cost. The DP relation is:

\displaystyle dp[n] = \min\{dp[n-k-1] + distribution(n, k)\text{ for }k \in [0, 2]\}

The solution is dp[N].


Comments

There are no comments at the moment.