You are given a tree consisting exactly of ?n vertices. Tree is a connected undirected graph with ?−1n−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 ∑?=1?????(?,?)⋅??∑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≤?≤2⋅1051≤n≤2⋅105).
The second line of the input contains ?n integers ?1,?2,…,??a1,a2,…,an (1≤??≤2⋅1051≤ai≤2⋅105), where ??ai is the value of the vertex ?i.
Each of the next ?−1n−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≤??,??≤?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.
Note
Picture corresponding to the first example:
You can choose the vertex 33 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=1212⋅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 00.
思路:
首先设定点1为根,设a[i]为点i的子树的权值和。dp[v]储存点在该点v处的∑i=dist(i,v)⋅ai。(先用dfs遍历树预处理处a[i],dp[i])。
接下来换根思想。u为该树的根节点,设v是u的子节点 。那么这时候如果换做v为根节点,那么这时候相当于v的子节点距离根节点的距离都减1,非子节点距离都加1.那么dp[v]就等于原有的值减去子节点权值和,加上非子节点权值和。即dp[v]=dp[v]+(dp[1]-dp[v])-dp[v]。
#include<iostream>
#include<cstdio>
#include<cstring>
#define ll long long
using namespace std;
const int maxn=2*1e5+10;
ll dp[200000+10];
ll a[maxn];
int head[maxn];
int n,cnt;
ll ans;
struct node{
int v,next;
}edge[maxn*2];
void add(int u,int v){
edge[cnt].v=v;
edge[cnt].next=head[u];
head[u]=cnt++;
}
void dfs(int u,int fa){
for(int i=head[u];i!=-1;i=edge[i].next){
int v=edge[i].v;
if(v!=fa){
dfs(v,u);
a[u]+=a[v];
dp[u]+=a[v]+dp[v];
}
}
}
void dfs2(int u,int fa){
if(u!=1)
dp[u]=dp[fa]+a[1]-2*a[u];
for(int i=head[u];i!=-1;i=edge[i].next){
int v=edge[i].v;
if(v!=fa){
dfs2(v,u);
}
}
if(ans<dp[u])ans=dp[u];
}
int main(){
int u,v;
cin>>n;
cnt=0;ans=0;
memset(head, -1, sizeof(head));
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++){
cin>>a[i];
}
for(int i=1;i<n;i++){
cin>>u>>v;
add(u,v);
add(v,u);
}
dfs(1,0);//预处理a[i],dp[i]
dfs2(1,0);//更新dp[i]查找最大值ans
cout<<ans<<endl;
return 0;
}