You are not logged in. Please login at to post your questions!


KRYP2 - Editorial



Author: Shivam Garg
Tester: Shiv Dhingra




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.

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 - Code

asked 17 Feb '18, 16:23

shivamg_isc's gravatar image

accept rate: 0%

edited 19 Feb '18, 14:57

toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text]( "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:


question asked: 17 Feb '18, 16:23

question was seen: 447 times

last updated: 05 Mar '18, 22:18