You are given a tree consisting exactly of n vertices. Tree is a connected undirected graph with n−1 edges. Each vertex v of this tree has a value av assigned to it.
Let dist(x,y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.
Let’s define the cost of the tree as the following value: firstly, let’s fix some vertex of the tree. Let it be v. Then the cost of the tree is dist(i,v)⋅ai
Your task is to calculate the maximum possible cost of the tree if you can choose v arbitrarily.
Input
The first line contains one integer n, the number of vertices in the tree (1≤n≤2⋅105).
The second line of the input contains n integers a1,a2,…,an (1≤ai≤2⋅105), where ai is the value of the vertex i.
Each of the next n−1 lines describes an edge of the tree. Edge i is denoted by two integers ui and vi, the labels of vertices it connects (1≤ui,vi≤n, ui≠vi).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum possible cost of the tree if you can choose any vertex as v.
Examples
input 1
output 1
input 2
output 2
Note
Picture corresponding to the first example:
You can choose the vertex 3 as a root, then the answer will be 2⋅9+1⋅4+0⋅1+3⋅7+3⋅10+4⋅1+4⋅6+4⋅5=18+4+0+21+30+4+24+20=121.
In the second example tree consists only of one vertex so the answer is always 0.
题目大意:给出一个具有n个点的无向图,给出 n-1条边,然后求出如果以一个点为树的根,那么这棵树的Cost是多少,Cost定义为 dist(i,v)⋅ai,dist(a,b)的含义就是两个点之间的距离
另外,数据保证该图联通
同学博客奉上
在以 1 为根节点的时候,如果这个根节点转移到与其相连的子节点,那么来说,和转移之前的节点相连的子树的节点的距离就要减小 1 ,假设a[t] 表示以 t 为根的子树的权值,那么来说,以之前的 1 为根的子树的权值就是a[1] , 如果是相连的子节点那么距离就要减少 a[i] , 然后对于那些非子节点的 Cost 就要增加 1,那么来说,增加的就是a[1] - a[i],所以说,总的变化就是
a[1] - a[i] - a[i]
则当前节点的Cost:
Cost[子节点] = Cost[父节点] + a[1] - a[i] - a[i]
深度优先搜索的时候遍历一下就行了,注意遍历的时候父节点子节点的关系问题
Code: