F.费用最高的树------树形dp

You are given a tree consisting exactly of nn vertices. Tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a value avav assigned to it.

Let dist(x,y)dist(x,y) be the distance between the vertices xx and yy. 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 vv. Then the cost of the tree is ∑i=1ndist(i,v)⋅ai∑i=1ndist(i,v)⋅ai.

Your task is to calculate the maximum possible cost of the tree if you can choose vv arbitrarily.

Input

The first line contains one integer nn, the number of vertices in the tree (1≤n≤2⋅1051≤n≤2⋅105).

The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤2⋅1051≤ai≤2⋅105), where aiai is the value of the vertex ii.

Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n1≤ui,vi≤n, ui≠viui≠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 vv.

Examples

input

Copy

8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8

output

Copy

121

input

Copy

1
1337

output

Copy

0

Note

Picture corresponding to the first example:F.费用最高的树------树形dp_第1张图片

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.

 

#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long ll;
//题解:两边dfs,第一遍,保存子节点到父节点的结果和全部子节点的val和,因为向上跟新一个节点,就相当于加上一次val。
//
//第二遍跟新父节点到子节点,也就是父节点的结果 减去 子节点累计的权值和 加上(总权值和 - 子节点的权值和)
#define INF 0x3f3f3f3f
#define maxn 200001
vector p[maxn];
ll val[maxn],dp[maxn],a[maxn],total=0,ans;
//第一遍dfs
void dfs(ll u,ll pa){
	val[u]=a[u];
	ll len=p[u].size();
	for(ll i=0;iu这条边过去的子节点权值 
		dp[u]+=val[v]+dp[v];
		//累计子节点权值 
		val[u]+=val[v];
	}
}
 
void dfs_plus(ll u,ll pa){
	ll len=p[u].size();
	for(ll i=0;iv这条边的与val[v]互补的权值的和
		dp[v]=dp[u]-val[v]+(total-val[v]);
		ans=max(ans,dp[v]);//存储最大的dp 
		dfs_plus(v,u);
	}
}
 
int main(){
	ll n;
	cin>>n;
	for(ll i=1;i<=n;i++){
		cin>>a[i];
		total+=a[i];
	}
	for(ll i=1;i>x>>y;
		p[x].push_back(y);
		p[y].push_back(x);
	}
	dfs(1,0);
	ans=dp[1];
	dfs_plus(1,0);
	cout<

 

你可能感兴趣的:(树形dp)