×

# KRYP2 - Editorial

Author: Shivam Garg
Tester: Shiv Dhingra

MEDIUM HARD

Mo's on Trees

# PROBLEM

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.

# EXPLANATION

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))$.

# SOLUTION

Setter'S Solution - Code

6211210
accept rate: 0%

 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• 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:

×15,684
×1,755
×1,250
×708
×116
×80
×15

question asked: 17 Feb '18, 16:23

question was seen: 447 times

last updated: 05 Mar '18, 22:18