AlgoUniversity
  • Go Back
Discussion
Subtree K Th Max :

Author

Ayush Gangwani

Difficulty Level : Medium

Submissions : 271

Asked In : PhonePe

Marks :15

: 9 | : 0

We have a rooted tree with $$$n$$$ vertices. The vertices are numbered $$$1$$$ through $$$n$$$, and the root is Vertex $$$1$$$. The $$$i^{th}$$$ edge connects Vertices $$$u$$$​ and $$$v$$$​. Vertex $$$i$$$ has an integer $$$x_i$$$​ written on it.

You need to answer $$$q$$$ queries of the following types:

  • $$$v$$$ $$$k$$$ — among the integers written on the vertices in the subtree rooted at Vertex $$$v$$$​, find the $$$k-th$$$ largest value.

Input

The first line of input contains two space separated integers $$$n$$$ $$$(1 \le n \le 10^5)$$$ and $$$q$$$ $$$(1 \le q \le 10^5)$$$.

The second line contains $$$n$$$ space separated integers $$$x_1,x_2,...x_n$$$ $$$(1 \le x_i \le 10^9)$$$— $$$x_i$$$ represents the value on node $$$i$$$ respectively.

The next $$$n-1$$$ lines contain two space separated integers $$$u$$$ and $$$v$$$ $$$(1 \le u,v \le n)$$$ each denoting an edge between vertices $$$u$$$ and $$$v$$$.

Finally, the next $$$q$$$ lines contain two space separated integers $$$x$$$ $$$(1 \le x \le n)$$$ and $$$k$$$ $$$(1 \le k \le 20)$$$ each denoting the queries.

Output

Print the answer to each query in a single line.

Examples

Input
5 2
1 2 3 4 5
1 4
2 1
2 5
3 2
1 2
2 1
Output
4
5
Input
6 2
10 10 10 9 8 8
1 4
2 1
2 5
3 2
6 4
1 4
2 2
Output
9
10
Input
4 4
1 10 100 1000
1 2
2 3
3 4
1 4
2 3
3 2
4 1
Output
1
10
100
1000

Note

For sample test case $$$1$$$, the tree given in this input is shown below.

  • For the $$$1^{st}$$$ query, the vertices in the subtree rooted at Vertex $$$1$$$ are Vertices $$$1,2,3,4,$$$ and $$$5$$$, so print the $$$2^{nd}$$$ largest value of the numbers written on these vertices — $$$4$$$.
  • For the $$$2^{nd}$$$ query, the vertices in the subtree rooted at Vertex $$$2$$$ are Vertices $$$2,3,$$$ and $$$5$$$, so print the $$$1^{st}$$$ largest value of the numbers written on these vertices — $$$5$$$.

You need to login to view your submissions.

You need to login to view all submissions.

Loading...

Result : Executed

Loading...

Feel something is wrong with the test cases?

Result : Accepted

Test Cases :

You need to Log In
We're glad that you want to attempt this problem!

But to Run or Submit the Problem, you need to Log In.

Continue to Log In
Challenge Submitted!

Your challenge has been submitted successfully.

You will get a response soon via WhatsApp or Email.

Challenge
Facing issue while trying to solve the problem! Don't worry, we got you covered!

Do let us know your issue.

Looks good!
Please enter your issue / feedback.

How do we get in touch with you?
Looks good!
Please enter your phone no.
Looks good!
Please enter your email address.