#abc359g. G - Sum of Tree Distance

G - Sum of Tree Distance

Score : 600600 points

问题陈述

给定一个有 NN 个顶点的树。第 ii 条边双向连接顶点 uiu_iviv_i

此外,给定一个整数序列 A=(A1,,AN)A=(A_1,\ldots,A_N)

这里,定义 f(i,j)f(i,j) 如下:

  • 如果 Ai=AjA_i = A_j,则 f(i,j)f(i,j) 是从顶点 ii 移动到顶点 jj 需要经过的最少边数。如果 AiAjA_i \neq A_j,则 f(i,j)=0f(i,j) = 0

计算以下表达式的值:

$\displaystyle \sum_{i=1}^{N-1}\sum_{j=i+1}^N f(i,j)$。

以上为大语言模型 kimi 翻译,仅供参考。

Problem Statement

You are given a tree with NN vertices. The ii-th edge connects vertices uiu_i and viv_i bidirectionally.

Additionally, you are given an integer sequence A=(A1,,AN)A=(A_1,\ldots,A_N).

Here, define f(i,j)f(i,j) as follows:

  • If Ai=AjA_i = A_j, then f(i,j)f(i,j) is the minimum number of edges you need to traverse to move from vertex ii to vertex jj. If AiAjA_i \neq A_j, then f(i,j)=0f(i,j) = 0.

Calculate the value of the following expression:

$\displaystyle \sum_{i=1}^{N-1}\sum_{j=i+1}^N f(i,j)$.

Constraints

  • 2N2×1052 \leq N \leq 2 \times 10^5
  • 1ui,viN1 \leq u_i, v_i \leq N
  • 1AiN1 \leq A_i \leq N
  • The input graph is a tree.
  • All input values are integers.

Input

The input is given from Standard Input in the following format:

NN

u1u_1 v1v_1

\vdots

uN1u_{N-1} vN1v_{N-1}

A1A_1 A2A_2 \ldots ANA_N

Output

Print the answer.

Sample Input 1

4
3 4
4 2
1 2
2 1 1 2

Sample Output 1

4

f(1,4)=2,f(2,3)=2f(1,4)=2, f(2,3)=2. For all other i,j (1i<jN)i, j\ (1 \leq i < j \leq N), we have f(i,j)=0f(i,j)=0, so the answer is 2+2=42+2=4.

Sample Input 2

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

Sample Output 2

19