Editorial for COCI '23 Contest 5 #2 Bitovi


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.

In the first subtask, the highest weight bit (if we consider all numbers as 15-bit numbers) is always 0. To transform one number into another through a sequence of moves, it is enough to set the highest bit to 1, arbitrarily change the other bits, and then revert the highest bit to 0. However, we must ensure that the number we obtain is not currently in set A.

In the second subtask, there will always exist a path (a sequence of moves) to transform any number into any other number, without changing the rest. Moreover, as long as |A| \le b, where b is the number of bits in the representation of each number, there exists a path from x to y for x \in A and y \notin A. Now, it is sufficient to find an arbitrary pair (x, y) such that x \in A \setminus B and y \in B \setminus A, and then change x to y. If such a pair does not exist, sets A and B are equal.

We solve the last two subtasks similarly. Let's consider an arbitrary pair (x, y) that satisfies the above condition and an arbitrary path from x to y without the restriction that it cannot contain elements from set A. Let z be an element from A on that path closest to the number y. Then, on the path from z to y, there are no elements from set A. Therefore, we can change z to y through a sequence of moves, and then recursively repeat this process for (x, z) until we obtain a simple path from the previous subtask. Finding all required variables is done in \mathcal{O}(N), the maximum possible length of the path is \mathcal{O}(Nb), and there are at most \mathcal{O}(N) such pairs, so the overall complexity of this algorithm is \mathcal{O}(N^2 b), which is sufficient to solve the third subtask.

Since the choice of the path is arbitrary, let's choose the shortest path whose length is not greater than the number of bits b. Then, the sum of the lengths of all paths is \mathcal{O}(Nb). Note that after executing the algorithm for (x, y), we will have x \in B, and every number that was in both A and B before executing the algorithm will still be in both sets. Therefore, we can iterate over the elements of set B, and for each number y \in B that is not in A, we call the algorithm, using any x \in A that is not in B. Such x's can be maintained in various ways, such as by using a set. The overall complexity is \mathcal{O}(Nb + N \log N).


Comments

There are no comments at the moment.