Editorial for COCI '16 Contest 7 #3 Igra


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.

We will construct a word letter by letter, starting from the first one, in a way that we try to place the lexicographically smallest letter to the current position. After we choose a letter, we need to check whether the remaining letters can be placed so that none of them match the same letter in Mirko's word (MR). Therefore, we are not interested in the order of these letters, but only if they can be arranged somehow.

Let a, b and c denote the number of remaining letters a, b and c, respectively, and A, B and C the number of remaining letters a, b and c in MR.

  1. Let's try to place k letters a to the positions of letters b in MR, i.e., reduce a and B by k.
  2. The remaining letters a we place to the positions of letters c in MR, i.e., reduce C by a and set a to 0.
  3. We set the remaining letters b in MR to letters c, i.e., reduce c by B and set B to 0.
  4. Now, we need to place the remaining letters c to the positions of letters a in MR, i.e., reduce A by c and set c to 0.

If we couldn't have made any of the previous moves, that means no solution exists for the chosen k. If we could have, we are left with checking whether letters b can be placed to the positions of letters a and c in MR. This will hold if A+C = b. In that case, the letters can be placed for this k and the check is done.

We will test this out for each k between 0 and B. If the check didn't succeed for any k, then it is impossible to place the remaining letters so that none of them match the same letter in Mirko's word, otherwise we can. This needs to be done for each of the N letters, so the total complexity is \mathcal O(N^2). We leave the linear solution as an exercise for the reader.


Comments

There are no comments at the moment.