HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Find a node with maximum distance from query node in a tree

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
maximumwithnodequerydistancefindfromtree

Problem

I solved this problem from codechef:
problem link

and now I want to change it a bit. Instead of find out the distance between node $u$ and $v$ I want to answer $k$ queries of the form: find node $u$ to which distance from node $v$ is maximum but I'm not able to see fast enough algorithm for it.
I think that heavy light decomposition is still my best option. Do you have any ideas?

Finding node to which distance is maximum in this way is $O(n)$ but the challenge here is that I have to answer to $k$ queries so the total complexity is $O(nk)$. I believe that this can be done in $O((n+k)\log n)$.

Solution

Start from any node and find (say, with a BFS) a farthest node from it; call it $u$. Then start from $u$ and find a farthest node from it; call it $v$. Nodes $u$ and $v$ achieve the absolute maximum distance in the tree.

Now with 2 more BFS, find the distances of all nodes from $u$, and the distances of all nodes from $v$. At this point you are ready to answer the queries: for each queried node $z$, the most distant node is either $u$ or $v$, depending on which has the larger distance. This solves your problem in $O(n + k)$ time.

Context

StackExchange Computer Science Q#84426, answer score: 2

Revisions (0)

No revisions yet.