The smallest path

3.6

5 votes
Advanced Algorithms, Algorithms, C++, Square Root Decomposition
Problem

You are given an undirected tree with N nodes and the tree is rooted at node 1. Each node has an integer value A[i] associated with it represented by an array A of size N.

Also, you are given Q queries of the following type:

  • uvk: Find the kth smallest value present on the simple path between node u and node v. If the number of nodes on the simple path between node u and node v is less than k, then print 1.

Input format

  • The first line contains two space-separated integers NQ denoting the number of nodes and queries respectively.
  • The second line contains N space-separated integers denoting array A.
  • Next N1 lines contain two space-separated integers denoting the edges of the tree.
  • Next Q lines contain three space-separated integers denoting the queries.

Output format

Print Q space-separated integers denoting the answer of queries.

Constraints

1N4×1041Q1051A[i]109

 

Sample Input
8 2
105 2 9 3 8 5 7 7
1 2
1 3
1 4
3 5
3 6
3 7
4 8
8 7 5
8 7 3
Sample Output
105 7
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation
  • Simple path between node 8 and node 7 is  8 - 4 - 1 -  3 - 7.
  • Values of nodes present on the simple path is [7, 3, 105, 9, 7].
  • 3-rd smallest value is 7.
  • 5-th smallest value is 105
Editor Image

?