CF1806E.Tree Master

普及/提高-

通过率:0%

AC君温馨提醒

该题目为【codeforces】题库的题目,您提交的代码将被提交至codeforces进行远程评测,并由ACGO抓取测评结果后进行展示。由于远程测评的测评机由其他平台提供,我们无法保证该服务的稳定性,若提交后无反应,请等待一段时间后再进行重试。

题目描述

You are given a tree with nn weighted vertices labeled from 11 to nn rooted at vertex 11 . The parent of vertex ii is pip_i and the weight of vertex ii is aia_i . For convenience, define p1=0p_1=0 .

For two vertices xx and yy of the same depth ^\dagger , define f(x,y)f(x,y) as follows:

  • Initialize ans=0\mathrm{ans}=0 .
  • While both xx and yy are not 00 :
    • ansans+axay\mathrm{ans}\leftarrow \mathrm{ans}+a_x\cdot a_y ;
    • xpxx\leftarrow p_x ;
    • ypyy\leftarrow p_y .
  • f(x,y)f(x,y) is the value of ans\mathrm{ans} .

You will process qq queries. In the ii -th query, you are given two integers xix_i and yiy_i and you need to calculate f(xi,yi)f(x_i,y_i) .

^\dagger The depth of vertex vv is the number of edges on the unique simple path from the root of the tree to vertex vv .

输入格式

The first line contains two integers nn and qq ( 2n1052 \le n \le 10^5 ; 1q1051 \le q \le 10^5 ).

The second line contains nn integers a1,a2,,ana_1, a_2, \ldots, a_n ( 1ai1051 \le a_i \le 10^5 ).

The third line contains n1n-1 integers p2,,pnp_2, \ldots, p_n ( 1pi<i1 \le p_i < i ).

Each of the next qq lines contains two integers xix_i and yiy_i ( 1xi,yin1\le x_i,y_i\le n ). It is guaranteed that xix_i and yiy_i are of the same depth.

输出格式

Output qq lines, the ii -th line contains a single integer, the value of f(xi,yi)f(x_i,y_i) .

输入输出样例

  • 输入#1

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

    输出#1

    33
    27
  • 输入#2

    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

    输出#2

    47
    53
    48
    36
    42
    36
    48
    14

说明/提示

Consider the first example:

In the first query, the answer is a4a5+a3a3+a2a2+a1a1=3+4+25+1=33a_4\cdot a_5+a_3\cdot a_3+a_2\cdot a_2+a_1\cdot a_1=3+4+25+1=33 .

In the second query, the answer is a6a6+a2a2+a1a1=1+25+1=27a_6\cdot a_6+a_2\cdot a_2+a_1\cdot a_1=1+25+1=27 .

首页