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 ∑i=1ndist(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
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
Input
1
1337
Output
0
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.
题意
sum(dist(u,v)*val[v]):从任意节点u到其它节点v的距离乘以该节点的权值之和,找出最大节点u;
分析
我们可以先dfs一遍,用于记录任意节点的和,并且记录val[i]:此节点的子节点权值之和(包括本身)dp【】每个节点到其他节点的权值之和,但在这次dfs中只能更新一个,所以我们需要再dfs一次,用来更新每个节点。
dp[v]:因为影响此值的只有父节点,所以我们只针对该点的父节点更新即可,父节点即向上节点的值是不需要更新的,所以从该节点出发或该父节点别的方向出发计算的值是不影响的,因为此节点要作为父节点了,所以要把其他节点带到该节点的值减去(此时只有父节点及向上节点带来的值减去即可)dp[fa(v)]-val[v],此时还不够,因为此节点向父节点出发的值还没计算,所以只需在加一遍除子节点的其他权值即可vv(各节点的总权值)-val[v];
#include<cstdio>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long ll;
#define maxn 200010
ll dp[maxn],a[maxn],val[maxn];
ll vv=0,ans=0;
vector<int >ve[maxn];
void dfs1(int u,int fa)
{
val[u]=a[u];
for(int i=0;i<ve[u].size();i++)
{
int v=ve[u][i];
if(fa==v)continue;
dfs1(v,u);
dp[u]+=val[v]+dp[v];
val[u]+=val[v];
}
}
void dfs2(int u,int fa)
{
ans=max(ans,dp[u]);
for(int i=0;i<ve[u].size();i++)
{
int v=ve[u][i];
if(v==fa)continue;
dp[v]=dp[u]-val[v]+(vv-val[v]);//从v出发的距离*权值之和
dfs2(v,u);
}
}
int main()
{
int n,u,v;
cin>>n;
for(int i=1;i<=n;i++)cin>>a[i],vv+=a[i];
for(int i=1;i<n;i++){
cin>>u>>v;
ve[u].push_back(v);
ve[v].push_back(u);
}
dfs1(1,-1);
ans=dp[1];
dfs2(1,-1);
printf("%lld\n",ans);
return 0;
}