To a tree, for each node u, there is a value of sum (dist (u, v) * val [v]), v is the other nodes, find the maximum value.
Tree dp
If u v is a child node, places v is the root of the subtree contribution is sub-tree and for u all nodes.
U is to first find the root of the subtree and weights. Sum [v], - can be considered while dfs while the answer, when transferred from u to v, the current value to be subtracted sum [v], plus the sum [u]
when the above two steps miss, the key is to calculate v , u is the equivalent of the child node v, the sum [u] - = sum [ v], sum [v] + = sum [u], turn a bit corresponding to the tree.
2e5 * 2e5 will burst int, to be explicit with LL transition
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 2e5 + 10;
int a[N],u,v,n;
vector<int> G[N];
LL tmp, ans,sum[N];
void dfs(int u,int fa,int st){
tmp += (LL)st * a[u];
sum[u] = a[u];
for(int i = 0;i<G[u].size();i++){
int v = G[u][i];
if(v == fa) continue;
dfs(v,u,st+1);
sum[u] += sum[v];
}
}
void mov(int u,int fa){
ans = max(ans,tmp);
for(int i = 0;i<G[u].size();i++){
int v = G[u][i];
if(v == fa) continue;
tmp -= sum[v];
tmp += (sum[u] - sum[v]);
sum[u] -= sum[v];
sum[v] += sum[u];
mov(v,u);
sum[v] -= sum[u];
sum[u] += sum[v];
tmp -= (sum[u] - sum[v]);
tmp += sum[v];
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin>>n;
for(int i = 1;i<=n;i++) cin>>a[i];
for(int i = 0;i<n-1;i++){
cin>>u>>v;
G[u].push_back(v);
G[v].push_back(u);
}
dfs(1,-1,0);
mov(1,-1);
cout<<ans;
return 0;
}