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

#SRD0000099. Tích vô hướng trên đường tổ tiên (Tree Master)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Tích vô hướng trên đường tổ tiên (Tree Master)

Tree Master

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a tree with nn vertices rooted at 11, numbered 11 to nn. Vertex ii has a positive integer weight aia_i. For i≥2i\ge2, its direct parent is pip_i; define p1=0p_1=0.

Two query vertices x,yx,y always have the same depth, defined as the number of edges from the root. Define f(x,y)f(x,y) by the following process:

  1. Set s=0s=0.
  2. While both xx and yy are nonzero, add ax⋅aya_x\cdot a_y to ss, then simultaneously set x←pxx\leftarrow p_x and y←pyy\leftarrow p_y.
  3. Once both vertices reach the artificial vertex 00, return ss.

For each of the qq queries containing x,yx,y, compute f(x,y)f(x,y). The two vertices may coincide, in which case the products are squares of weights along the path to the root.

Input

The first line contains n,qn,q. The second line contains a1,…,ana_1,\ldots,a_n. The third line contains p2,…,pnp_2,\ldots,p_n. Each of the next qq lines contains two vertices x,yx,y of equal depth.

Output

For each query, print the integer f(x,y)f(x,y) on its own line. Results may exceed 32-bit signed range.

Subtasks

  • Subtask 1 (10 points): n≤40n\le 40, q≤40q\le 40.
  • Subtask 2 (20 points): n≤2000n\le 2000, q≤2000q\le 2000.
  • Subtask 3 (30 points): n≤20000n\le 20000, q≤20000q\le 20000.
  • Subtask 4 (40 points): n≤100000n\le 100000, q≤100000q\le 100000.

Conditions shared by all subtasks: For every group: 2≤n≤1000002\le n\le100000, 1≤q≤1000001\le q\le100000, 1≤ai≤1000001\le a_i\le100000, 1≤pi<i1\le p_i<i for i≥2i\ge2, 1≤x,y≤n1\le x,y\le n, and depth[x]=depth[y]\mathrm{depth}[x]=\mathrm{depth}[y].

Examples

Example 1

Input

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

Output

33
27

Explanation

For (4,5)(4,5), the ancestor chains are 4→3→2→14\to3\to2\to1 and 5→3→2→15\to3\to2\to1. The sum is a4a5+a32+a22+a12=3+4+25+1=33a_4a_5+a_3^2+a_2^2+a_1^2=3+4+25+1=33. For (6,6)(6,6) it is a62+a22+a12=1+25+1=27a_6^2+a_2^2+a_1^2=1+25+1=27.

Example 2

Input

14 8
3 2 5 3 1 4 2 2 2 5 5 5 2 4
1 2 3 1 1 4 7 3 3 1 5 3 8
4 4
4 10
13 10
3 12
13 9
3 12
9 10
11 5

Output

47
53
48
36
42
36
48
14

Explanation

Example 2 contains repeated queries, including (3,12)(3,12) twice, with answer 3636 both times. A query does not modify any tree data.