#P2726. [SHOI2005] 树的双中心

[SHOI2005] 树的双中心

Description

Given a tree T=(V,E)T=(V,E), where VV is the set of nodes and EE is the set of edges.

For each node vVv \in V, there is a weight function W(v)W(v) whose values are positive integers.

Let d(u,v)d(u,v) be the distance between nodes uu and vv, meaning the number of edges on the unique path between them. If uu and vv are the same node, then d(u,v)=0d(u,v)=0.

Your task is to find two distinct nodes xx and yy that minimize the following expression:

$$S(x,y)=\sum_{v\in V} (W(v)\cdot \min\{ d(v,x),d(v,y)\})$$

Input Format

  • The first line contains NN (1<N5×1041 < N \le 5\times 10^4), the number of nodes in the tree. The nodes are numbered from 11 to NN.
  • The next N1N-1 lines each contain two integers U,VU, V, indicating there is an edge between UU and VV.
  • Then NN more lines follow. Each line contains a positive integer; on the ii-th of these lines, the integer gives the weight W(i)W(i) of node ii.
  • It is guaranteed that the depth of the tree does not exceed 100100.

Output Format

Output the minimal value of S(x,y)S(x,y). The result is guaranteed not to exceed 10910^9.

5
1 2
1 3
3 4
3 5
5
7
6
5
4
14

Hint

In the sample, the two chosen centers are nodes 22 and 33.

Translated by ChatGPT 5