#abc348e. E - Minimize Sum of Distances

E - Minimize Sum of Distances

Score: 475475 points

问题陈述

给定一个有 NN 个顶点的树。顶点编号为 11NN,第 ii 条边连接顶点 AiA_iBiB_i

你还给定了一个正整数序列 C=(C1,C2,,CN)C = (C_1, C_2, \ldots ,C_N),长度为 NN。设 d(a,b)d(a, b) 为顶点 aabb 之间的边数,对于 x=1,2,,Nx = 1, 2, \ldots, N,设 $\displaystyle f(x) = \sum_{i=1}^{N} (C_i \times d(x, i))$。找出 min1vNf(v)\displaystyle \min_{1 \leq v \leq N} f(v)

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

Problem Statement

You are given a tree with NN vertices. The vertices are numbered 11 to NN, and the ii-th edge connects vertices AiA_i and BiB_i.

You are also given a sequence of positive integers C=(C1,C2,,CN)C = (C_1, C_2, \ldots ,C_N) of length NN. Let d(a,b)d(a, b) be the number of edges between vertices aa and bb, and for x=1,2,,Nx = 1, 2, \ldots, N, let $\displaystyle f(x) = \sum_{i=1}^{N} (C_i \times d(x, i))$. Find min1vNf(v)\displaystyle \min_{1 \leq v \leq N} f(v).

Constraints

  • 1N1051 \leq N \leq 10^5
  • 1Ai,BiN1 \leq A_i, B_i \leq N
  • The given graph is a tree.
  • 1Ci1091 \leq C_i \leq 10^9

Input

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

NN

A1A_1 B1B_1

A2A_2 B2B_2

\vdots

AN1A_{N - 1} BN1B_{N - 1}

C1C_1 C2C_2 \cdots CNC_N

Output

Print the answer in one line.

Sample Input 1

4
1 2
1 3
2 4
1 1 1 2

Sample Output 1

5

For example, consider calculating f(1)f(1). We have d(1,1)=0,d(1,2)=1,d(1,3)=1,d(1,4)=2d(1, 1) = 0, d(1, 2) = 1, d(1, 3) = 1, d(1, 4) = 2.
Thus, $f(1) = 0 \times 1 + 1 \times 1 + 1 \times 1 + 2 \times 2 = 6$.

Similarly, f(2)=5,f(3)=9,f(4)=6f(2) = 5, f(3) = 9, f(4) = 6. Since f(2)f(2) is the minimum, print 5.

Sample Input 2

2
2 1
1 1000000000

Sample Output 2

1

f(2)=1f(2) = 1, which is the minimum.

Sample Input 3

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

Sample Output 3

56