ktree

Time limit: 3s
Memory limit: 256MB
Input:
Output:

You are given a tree with NN nodes indexed from 11 to NN, rooted in node 11. Each node has a value ViV_i.

Giorgio asked you to answer QQ queries of the form u,v,ku,v,k: Which is the kk-th largest value among those of the nodes on the path between nodes uu and vv (including endpoints)?
Here, k=1k=1 corresponds to the largest value, k=2k=2 to the second largest, etc.

Input data

The first line contains the integer NN: the number of nodes in the tree.

The second line contains NN integers ViV_i: the ii-th integer represents the value of node ii.

The third line contains N1N-1 integers PiP_i: the ii-th integer represents Pi+1P_{i+1}, the parent of node i+1i+1.

The fourth line contains a single integer QQ: the number of queries.

The following QQ lines contain 33 integers uj,vj,kju_j,v_j,k_j each, representing a query.

Output data

You have to output QQ lines, the jj-th of them containing a single integer: the answer to the jj-th query.

Constraints and Clarifications

  • 2N250 0002 \le N \le 250 \ 000.
  • 1ViN1 \le V_i \le N for each i=1Ni=1 \ldots N.
  • 1PiN1 \le P_i \le N for each i=2Ni=2 \ldots N.
  • 2Q250 0002 \le Q \le 250 \ 000.
  • 1uj,vjN1 \le u_j, v_j \le N for each j=1Qj=1 \ldots Q.
  • 1kjdist(uj,vj)+11 \le k_j \le \textrm{dist}(u_j,v_j)+1 for each j=1Qj=1 \ldots Q.
# Score Restrictions
1 0 Examples.
2 8 N,Q1 000N,Q \le 1 \ 000
3 11 N,Q40 000N,Q \le 40 \ 000, Pi=i1P_i = i-1 for each i=2Ni = 2 \ldots N
4 18 N,Q40 000N,Q \le 40 \ 000
5 13 N,Q100 000N,Q \le 100 \ 000, Pi=i1P_i = i-1 for each i=2Ni = 2 \ldots N}
6 20 N,Q100 000N,Q \le 100 \ 000
7 12 Pi=i1P_i = i-1 for each i=2Ni = 2 \ldots N
8 18 No additional limitations.

Example 1

stdin

6
3 6 6 6 6 6
5 1 1 1 1
5
4 2 2
2 4 2
1 1 1
4 3 2
4 3 1

stdout

6
6
3
6
6

Explanation

In the first sample case:

  • In the first query, nodes 4,1,5,2{4, 1, 5, 2} are on the path between 44 and 22, their values are, respectively, 6,3,6,6{6,3,6,6}. The second largest of them is 66.
  • In the second query, nodes 2,5,1,4{2, 5, 1, 4} are on the path between 22 and 44, their values are, respectively, 6,6,3,6{6,6,3,6}. The second largest of them is 66.
  • In the third query, only node 11 is on the path between 11 and 11. Its value is 33, the largest value on the path is therefore 33.
  • In the fourth query, nodes 4,1,3{4, 1, 3} are on the path between 44 and 33, their values are, respectively, 6,3,6{6,3,6}. The second largest of them is 66.
  • In the fifth query, nodes 4,1,3{4, 1, 3} are on the path between 44 and 33, their values are, respectively, 6,3,6{6,3,6}. The second largest of them is 66.

Example 2

stdin

10
5 10 1 1 2 5 9 8 2 9
8 2 7 9 5 1 1 8 5
10
10 3 2
1 4 2
6 8 1
3 4 2
2 9 2
9 7 2
3 3 1
6 4 4
5 5 1
3 8 1

stdout

9
5
8
9
8
8
1
5
2
10

Log in or sign up to be able to send submissions!