Editorial for Balkan OI '11 P4 - Compare
Submitting an official solution before solving the problem yourself is a bannable offence.
There are several solutions for this problem. The best solution the Scientific Committee
has uses , but we believe that
is also achievable and deserves more than
.
- A simple
solution:
We consider a binary tree that has leaves.
: we set all the nodes from leaf "
" to the root to
.
: Our goal is to determine the lowest common ancestor (LCA) for leaf
and
leaf
. Since the whole path from the root to the leaf is set to
, we can do a binary search.
Once we have the LCA we can return
,
or
.
The next solutions use one-hot encoding.
This encoding uses bits for representing a number from
to
. For a given number
, we only set the bit
to
and leave the rest set to
. The advantage of this method is
that we only need to write
bit. While reading a value could take
reads (we look
for the bit set to
), comparing is a little faster. It takes
reads. We only need to
search from the current position to the closest end (
or
).
- Some tree solutions (
):
We change the simple binary tree from the previous solution. We still have at least
leaves, but the internal nodes will have a variable number of children. For instance let's
assume that we have
levels and the number of children for each level is
,
,
,
,
and
. We chose the degree for each level such that
.
To encode a value in a node, we use the one-hot encoding.
Let's consider .
: we set all the nodes from leaf "
" to the root to
.
, since we have
nodes and encoding takes
bit_set()
call.
: Considering the same representation for
again we look for LCA. However
this time we do a top-down traversal. As soon as the bit we expect to be set to
is
, we
try to determine if
is higher or lower.
Worst case is when the last bit is not set to . In this case, we need to read an additional bit.
, since we have
nodes and an additional
bit_get()
.
- Further optimizations (
):
For the previous solution, we observe that the worst case is achieved when we miss the bit in the last node.
If we choose then
becomes
. This solution
also works if comparing a one-hot encoding is done in
reads and not
.
- Breaking the
symmetry (
):
Instead of levels for our tree, we chose
levels of degree:
.
becomes
and
becomes
.
This solution uses the optimization.
For a given set of maximum branching factors, the formula for is:
num_levels + max(branching_factor_on_level[i]/2 + 1 + i for i in range(0, num_levels))
with product(branching_factor_on_level(i)) > 4095
- Mixed-radix
All the above tree solutions don't really need a tree. For instance, let's pick the
solution above.
We can encode the value from the root in the bits from to
, the value from the node
on the second level in the memory from
to
and so on.
Comments