亚历山德拉和两棵树的问题

亚历山德拉和两棵树的问题

问题描述:

Description
Alexandra and her little brother have two rooted trees. For each tree, node 1 is the root, and every other node has its father's index less than itself. Also, there are weights on the nodes. Two nodes in different trees can have the same weight, buf two nodes in the same tree can't.
Now given the two trees and Q queries. Each query follows the format "u1 v1 u2 v2". Let S1 be the set of all node weights on the paths between u1 and v1 on the first tree, S2 be the set of all node weights on the paths between u2 and v2 on the second tree. You should output the number of elements in both S1 and S2. (e.g. the size of the intersection of S1 and S2)

Input
There are multiple test cases (no more than 50).
For each case, the first three lines describe the first tree. The first line only contains an integer N, the number of the nodes.
The second line contains N-1 integers, the i-th number is the father of node i+1.
The third line contains N integers, the i-th number is the weight of node i.
Next three lines have the same format, describing the second tree.
Next line only contains an integer Q.
Next Q lines, each line contains four integers u1,v1,u2,v2.
1≤N1,N2≤100,000.
For each tree, 1≤Pi1 and Pi is the father of i.
For each node, 0≤weight≤1,000,000,000.
1≤Q≤50,000.
1≤u1,v1≤N1,1≤u2,v2≤N2.
Number of cases with max(N1,N2,Q)≥1,000 is no more than 5.
Huge data. Fast I/O may be needed.

Output
For each query, output the requested answer.

Sample Input
3
1 2
1 2 3
3
1 2
1 2 3
3
1 2 1 2
1 2 1 3
1 2 2 3
1

1
1

1
1
1 1 1 1

Sample Output
2
2
1
1