Editorial for Baltic OI '01 P6 - Teleports
Submitting an official solution before solving the problem yourself is a bannable offence.
We will call Bornholm and Gotland and respectively. The first step of our algorithm is setting all the teleports on in receiving mode, and all teleports on in sending mode.
Why is this solution not good? The only thing that is wrong is that some receiving teleports on are useless — there are no teleports sending to them. We will maintain this invariant — after each step the solution will be OK except that some receiving teleports on will be useless.
In each step we choose a receiving teleport on with no teleports sending to it. If there are no such teleports, we are finished. Let's call the teleport we have chosen . We switch the teleport to sending mode. Let be the destination of — is a teleport on . If is in receiving mode, all is fine — the invariant is true. Otherwise we just switch to receiving mode. We can make another receiving teleport on useless this way, but the invariant is still true.
At the end there are no useless teleports left, so we have a correct solution.
At each step the number of receiving teleports on decreases by , so we will make at most steps.
To be able to make each step in time, we introduce an array , in which we store for each teleport on the number of teleports sending to it. We also keep track of all useless receiving teleports on — in the sample solution they are kept on a stack. In each step we just take a teleport from the stack, switch it to sending mode, possibly change the mode of its destination teleport and update one entry in the array .
Reading the input and the initial step take time, therefore time complexity of the whole algorithm is .
Comments