Editorial for CCC '20 S4 - Swapping Seats
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
Subtask 1
Let us designate an arbitrary index
This means that we need to do only as many moves as there are Bs in the A section. Since there are no Cs, we only need to swap any Bs in the A section with As in the B section, and since they correspond 1 to 1, that is our answer.
For the first subtask, we brute force all values of
Time Complexity:
Subtask 2
For the second subtask, we count the number of Bs using a Prefix Sum Array. Let
Time Complexity:
Subtask 3
For this subtask, we have to consider Cs. We take a different approach.
We go through all of the permutations of ABC. Without loss of generality, assume our permutation is ABC. The other 5 cases are analogous. Then we let the first
We now simulate the swaps. For each element in the A section that is not an A, we swap it with an A in the corresponding section if we can. If we cannot, we can swap it with a random A from the other section. We do the same for the B section, and we have our answer.
For this solution, we have to keep track of the positions of each letter in each section. We can do this with 3 vectors for the B and C sections, for 6 vectors total.
Time Complexity:
Full Solution
For full marks, we build on the solution from the second subtask.
Let
Note that now for any index
Then the B section is from
In this case, we must move all non-As from the A section and all non-Bs from the B section. However, note that we can save moves by swapping As in the B section with Bs from the A section. Thus, our answer for a given value of
We can use a PSA to compute the
Time Complexity:
Comments
I've found an easier expression for the number of swaps required:
. Here is the derivation.
Notice that
. Therefore the expression can be further rewritten as:
I think that this expression lends itself to an easier (albeit less rigorous) intuition: first swap all of the Cs in the A and B sections back into the C section, then fix up the A and B sections by making swaps between them.