KRYP2 - Editorial


Author: [Shivam Garg][3]
Tester: [Shiv Dhingra][4]




Mo’s on Trees


Given a tree, for each query comprising a path in the tree, it is required to answer the minimum absolute difference between any two distinct nodes on that path.


In order to solve this problem, Mo’s algorithm on trees can be implemented.
In order to gain more insight into this algorithm, refer this [excellent source][5].

As explained in the above-mentioned post, we, first of all, need to flatten the tree and compute the inTime[ ] and outTime [ ] via DFS. Mo’s algorithm can be implemented over this contiguous interval.

Now, according to the algorithm, queries can be computed, as we do not count the nodes which appear twice.

Now, in order to compute the minimum absolute difference of squared value between any 2 distinct nodes, there are various ways.

One of them is via the use of 2 multisets. The first multiset stores the squared values of the nodes. The second multiset stores the difference between closest/adjacent values in the first multiset.

In case a new element is inserted into multiset 1, not more than 2 new differences will be generated. These will be inserted in multiset 2. The same case holds when an element has to be deleted from multiset 1.

The answer to each query is the first element of multiset 2.

This question can also be solved by the use of Segment Tree. Whenever an element is to be inserted or removed, carry out the update operation in segment tree. Also, at each node compute the minimum absolute difference of the squared value between its constituent leaf nodes.

The complexity of multiset/segment tree is O(Log (N)), and that of Mo’s on Trees algorithm is O(Q \sqrt{N}). So, the overall complexity turns out to be O(Q \sqrt{N}Log (N)).


Setter’S Solution -