Path Maximum

5

1 votes
Problem

Given an undirected tree with N nodes and (N1) edges rooted at node 1.

We are given Q queries of type :

u v

where we need to find the maximum node value among the nodes present in the simple path between nodes u and v.(including u and v).

Note: Since this is a tree, there will be exactly one path between a pair of nodes. The simple path means that one path. 

Example

If N = 5, edge = [(1,2),(1,5),(1,4),(3,5)], Q = 2.

  • If query 1 is 1 3. Then the simple path between node 1 and 3 is 1 - 5 - 3. The maximum value node on a simple path is 5.
  • If query 2 is 1 2. Then the simple path between node 1 and 2 is 1 - 2. The maximum value node on a simple path is 2.

Input :
1. First line contain integer  N, denoting number of nodes in tree.
2. Next N - 1 lines contain two space separated integers u v, denoting an edge between node u and v.
3. Next line contain integer Q, denoting number of queries.
3. Next Q lines contain two space separated integers u v, denoting query.

Constraints :
2 <= N <= 10000
1 <= Q <= 100000

Output :
For each query, print the maximum value node on simple path between two nodes.

Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

For 1 - 5 -> Simple Path is 1 - 2 - 3 - 4 - 5 . Maximum value node is 5

For 3 - 4 -> Simple Path is 3 - 4 . Maximum value node is 4

Editor Image

?