Editorial for COCI '23 Contest 5 #2 Bitovi
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 -bit numbers) is always
. To
transform one number into another through a sequence of moves, it is enough to set the highest bit to
,
arbitrarily change the other bits, and then revert the highest bit to
. However, we must ensure that the
number we obtain is not currently in set
.
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 , where
is the number of bits
in the representation of each number, there exists a path from
to
for
and
. Now, it is
sufficient to find an arbitrary pair
such that
and
, and then change
to
. If
such a pair does not exist, sets
and
are equal.
We solve the last two subtasks similarly. Let's consider an arbitrary pair that satisfies the above
condition and an arbitrary path from
to
without the restriction that it cannot contain elements from
set
. Let
be an element from
on that path closest to the number
. Then, on the path from
to
,
there are no elements from set
. Therefore, we can change
to
through a sequence of moves, and then
recursively repeat this process for
until we obtain a simple path from the previous subtask. Finding
all required variables is done in
, the maximum possible length of the path is
, and there
are at most
such pairs, so the overall complexity of this algorithm is
, 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 . Then, the sum of the lengths of all paths is
. Note that after executing the
algorithm for
, we will have
, and every number that was in both
and
before executing
the algorithm will still be in both sets. Therefore, we can iterate over the elements of set
, and for each
number
that is not in
, we call the algorithm, using any
that is not in
. Such
's can be
maintained in various ways, such as by using a
set
. The overall
complexity is .
Comments