MathWorksOA #3
Rooted Distances (Re-rooting DP)
Estimated HardJudge-ready
Topics (AI-labelled)DP BasicsTree Traversal
Given a tree and a weight a[v] for each vertex. The beauty of vertex v is the sum of dist(u,v)×a[u] over all vertices u. Output the maximum beauty over all vertices.
This site uses a standard input/output protocol.
Input
The first line contains n; the second line contains n weights; the next n−1 lines give the edges u v (1-based). Constraints added by this site: 1≤n≤100000, 0≤a[i]≤10^9.
Output
Output the maximum beauty.
Example 1
Input:
2
3 4
1 2
Output:
4
Example 2
Input:
3
1 2 3
1 2
2 3
Output:
8
Example 3
Input:
4
0 0 7 1
1 2
2 3
2 4
Output:
16
Editorial
Loading solution…