Under construction

Still being built. Things may change

K-th smallest weight on a tree path

Time limit2sMemory limit512 MB

Summary
For each query, print the k-th smallest vertex weight on the unique tree path between two vertices.
Level

Hard8 of 10

Topics
Tree, Binary search, Prefix sum, Implementation
Solved
No attempts yet

Problem

You are given a tree with NN vertices. A tree is a connected undirected graph with no cycle. Vertices are numbered from 1 to NN, edges are numbered from 1 to N−1N-1, and every vertex carries one weight.

Write a program that answers the following query.

  • u v k: print the kk-th smallest weight among the weights of the vertices on the path from vertex uu to vertex vv.

A tree has exactly one path between two vertices, and that path includes both endpoints uu and vv. Equal weights on different vertices are counted separately when ranking. If the weights on the path are 3, 7, 7, 9, then both the 2nd smallest and the 3rd smallest value are 7.

Input

The first line contains the number of vertices NN. (2≤N≤100,0002 \le N \le 100{,}000)

The second line contains the weights of vertex 1 through vertex NN in order. Each weight is a natural number not greater than 1,000,0001{,}000{,}000.

Each of the next N−1N-1 lines contains two vertex numbers uu and vv joined by edge ii.

The next line contains the number of queries MM. (1≤M≤100,0001 \le M \le 100{,}000)

Each of the next MM lines contains one query in the form u v k. Both uu and vv are vertex numbers and they may be equal. kk is a natural number not greater than the number of vertices on the path from uu to vv.

Output

Print the answer to each query on its own line, in the order the queries are given.

Examples2

  1. Example 1

    Input
    8
    105 2 9 3 8 5 7 7
    1 2
    1 3
    1 4
    3 5
    3 6
    3 7
    4 8
    5
    2 5 1
    2 5 2
    2 5 3
    2 5 4
    7 8 2
    
    Expected output
    2
    8
    9
    105
    7
    
  2. Example 2

    Input
    2
    1000000 1
    1 2
    5
    1 1 1
    2 2 1
    1 2 1
    1 2 2
    2 1 2
    
    Expected output
    1000000
    1
    1
    1000000
    1000000