PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#SRD0000091. Ghép cặp theo sở thích (Dating)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Ghép cặp theo sở thích (Dating)

Dating

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

The town of BubbleLand contains nn houses numbered from 11 through nn. There are n−1n-1 bidirectional roads, with exactly one simple path between any two houses.

Each house contains exactly one resident, either a boy or a girl. The resident of house ii has a favorite number fif_i. A valid couple consists of one boy and one girl from different houses with equal favorite numbers; the order of the two people does not matter.

For each query (a,b)(a,b), consider only the residents of houses on the unique path from aa to bb, including both endpoints. Count how many valid couples can be formed using these residents.

Input

  • The first line contains nn.
  • The next line contains nn values gig_i, where 11 denotes a boy and 00 a girl at house ii.
  • The next line contains nn favorite numbers fif_i.
  • The following n−1n-1 lines each contain u,vu,v, describing a bidirectional road between the houses.
  • The next line contains qq.
  • The last qq lines each contain query endpoints a,ba,b.

Output

For each query, print the number of boy–girl couples with matching favorite numbers on the corresponding path.

Subtasks

  • Subtask 1 (10 points): n≤35n\le 35, q≤50q\le 50.
  • Subtask 2 (20 points): n≤600n\le 600, q≤600q\le 600.
  • Subtask 3 (30 points): n≤10000n\le 10000, q≤10000q\le 10000.
  • Subtask 4 (40 points): n≤100000n\le 100000, q≤100000q\le 100000.

Complete conditions for all subtasks, subject to the tighter limits above: 1≤n,q≤1051\le n,q\le 10^5, gi∈{0,1}g_i\in\{0,1\}, 1≤fi≤1091\le f_i\le 10^9, 1≤u,v,a,b≤n1\le u,v,a,b\le n.

Examples

Input

7
1 0 0 1 0 1 0
9 2 9 2 2 9 9
2 6
1 2
4 2
6 5
3 6
7 4
2
1 3
7 5

Output

2
3

Explanation

The path from house 11 to house 33 is 1→2→6→31\to2\to6\to3. Its residents have pairs (gender, favorite number) (1,9),(0,2),(1,9),(0,9)(1,9),(0,2),(1,9),(0,9). The girl in house 33 matches the boys in houses 11 and 66, yielding 2 couples.

The path from house 77 to house 55 is 7→4→2→6→57\to4\to2\to6\to5. Its three couples are (7,6)(7,6), with favorite number 99, and (4,2)(4,2), (4,5)(4,5), with favorite number 22. Thus the second answer is 3.