Editorial for COI '08 #2 Otoci
Submitting an official solution before solving the problem yourself is a bannable offence.
Suppose that all bridges have already been built and that islands and bridges form not just a tree, but a chain.
Now the number of penguins on islands can be kept in an array of integers. If we build a Fenwick tree or interval tree over this array of integers, we can efficiently change the number of penguins on an island and calculate the sum of numbers in an interval. The commands penguins
and excursion
in this simpler variant can be processed in bridge
does not appear in this variant so the overall complexity is
Now let the graph be a tree. In order to efficiently process penguins
and excursion
commands, we need to decompose the tree into a set of chains. There are many ways to do that, one of which (called heavy-light decomposition) is:
Choose an arbitrary node as the root of the tree. Now calculate for each node the number of nodes in its subtree. From each node with children, the child node with the largest degree is chosen and the edge connecting the parent and child is dubbed heavy. These heavy edges form chains. All other edges are called light.
This decomposition can be found in
Let depth(A)
be the depth of node
Let dad(A)
be the parent of node
Let chain(A)
be the chain node
Let first(L)
be the topmost node on chain
The following algorithm calculates the number of penguins between nodes
output = 0
while chain(A) ≠ chain(B):
if depth(first(chain(A))) < depth(first(chain(B))):
swap A and B
output = output + chain(A).count(first(chain(A)), A)
A = dad(first(chain(A)))
output = output + chain(A).count(A, B)
In other words, while
By decomposing the tree and building a data structure over the vertices on each chain (as in the previously described simpler variant of the problem), the complexity of the penguins
command remains excursion
command becomes
Now reintroduce the bridge
command. For each component, we need to maintain some sort of decomposition into chains.
Let
To fix this, we can rebuild the decomposition of a component when it becomes too unbalanced. One way to do this is to make the algorithm introspective – it can keep track of the number of steps needed to process penguins
commands. When this number goes over
Comments