E - Minimize Sum of Distances 解説 /

実行時間制限: 2 sec / メモリ制限: 1024 MB

配点 : 475475

問題文

NN 頂点からなる木が与えられます。頂点は 11 から NN までの番号がついており、 ii 番目の辺は頂点 Ai,BiA_i, B_i を結んでいます。

長さ NN の正整数列 C=(C1,C2,,CN)C = (C_1, C_2, \ldots ,C_N) が与えられます。d(a,b)d(a, b) を頂点 a,ba, b の間にある辺の数とし、 x=1,2,,Nx = 1, 2, \ldots ,N に対して f(x)=i=1N(Ci×d(x,i))\displaystyle f(x) = \sum_{i=1}^{N} (C_i \times d(x, i)) とします。min1vNf(v)\displaystyle \min_{1 \leq v \leq N} f(v) を求めてください。

制約

  • 1N1051 \leq N \leq 10^5
  • 1Ai,BiN1 \leq A_i, B_i \leq N
  • 与えられるグラフは木である。
  • 1Ci1091 \leq C_i \leq 10^9

入力

入力は以下の形式で標準入力から与えられる。

NN
A1A_1 B1B_1
A2A_2 B2B_2
\vdots
AN1A_{N - 1} BN1B_{N - 1}
C1C_1 C2C_2 \cdots CNC_N

出力

答えを一行に出力せよ。


入力例 1Copy

Copy
4
1 2
1 3
2 4
1 1 1 2

出力例 1Copy

Copy
5

例として、 f(1)f(1) を求めることを考えます。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 です。
よって、 f(1)=0×1+1×1+1×1+2×2=6f(1) = 0 \times 1 + 1 \times 1 + 1 \times 1 + 2 \times 2 = 6 となります。

同様に、 f(2)=5,f(3)=9,f(4)=6f(2) = 5, f(3) = 9, f(4) = 6 です。f(2)f(2) が最小なので 5 を出力します。


入力例 2Copy

Copy
2
2 1
1 1000000000

出力例 2Copy

Copy
1

f(2)=1f(2) = 1 で、これが最小です。


入力例 3Copy

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

出力例 3Copy

Copy
56

Score: 475475 points

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 f(x)=i=1N(Ci×d(x,i))\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 1Copy

Copy
4
1 2
1 3
2 4
1 1 1 2

Sample Output 1Copy

Copy
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×1+1×1+1×1+2×2=6f(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 2Copy

Copy
2
2 1
1 1000000000

Sample Output 2Copy

Copy
1

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


Sample Input 3Copy

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

Sample Output 3Copy

Copy
56


2024-04-07 (日)
22:10:07 +00:00