PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#LCA0000006. Chi phí lớn nhất trên cây (Tree with Maximum Cost)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Chi phí lớn nhất trên cây (Tree with Maximum Cost)

Tree with Maximum Cost

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

An undirected tree has nn vertices. Vertex ii carries a positive weight aia_i, and each edge has unit length.

If a station is placed at vertex uu, its cost is the sum of av⋅d(u,v)a_v\cdot d(u,v) over all vertices vv, where d(u,v)d(u,v) is the number of edges between uu and vv.

Choose the station vertex to maximize this cost.

Input

  • The first line contains nn.
  • The second line has nn vertex weights a1,…,ana_1,\ldots,a_n.
  • Each of the next n−1n-1 lines contains an undirected edge ui,viu_i,v_i.

Output

Print the maximum possible cost.

Subtasks

  • Subtask 1 (20 points): n≤30n\le30; 1≤n≤2⋅1051\le n\le2\cdot10^5; 1≤ai≤2⋅1051\le a_i\le2\cdot10^5.
  • Subtask 2 (30 points): n≤1000n\le1000; 1≤n≤2⋅1051\le n\le2\cdot10^5; 1≤ai≤2⋅1051\le a_i\le2\cdot10^5.
  • Subtask 3 (50 points): 1≤n≤2⋅1051\le n\le2\cdot10^5; 1≤ai≤2⋅1051\le a_i\le2\cdot10^5.

Examples

Input

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

Output

121

Explanation

Considering all possible station vertices and summing weighted distances yields a maximum cost of 121121.