CodeForces - 1092F Tree with Maximum Cost 树形dp

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

.题意:一个树,没个点都有权值,对于一节点k,定义f[k] 为 其他节点p到该点的距离*val[p] 的和,输出最大的f[k]

题解:两边dfs,第一遍,保存子节点到父节点的结果和全部子节点的val和,因为向上跟新一个节点,就相当于加上一次val。

第二遍跟新父节点到子节点,也就是父节点的结果 减去 子节点累计的权值和 加上(总权值和 - 子节点的权值和)

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
#define PI acos(-1)
#define M(a) memset(a,0,sizeof(a))
const int N=2e5+10;
ll dp[N],a[N],val[N];
int n;
vector<int> v[N];
ll vv;
void dfs1(int u,int f)
{
	val[u]=a[u];
	for(int i=0;i<v[u].size();i++)
	{
		int to=v[u][i];
		if(to==f) continue;
		dfs1(to,u);
		dp[u]+=val[to]+dp[to];
		val[u]+=val[to];
	}
}
ll ans;
void dfs2(int u,int f)
{
	ans=max(ans,dp[u]);
	for(int i=0;i<v[u].size();i++)
	{
		int to=v[u][i];
		if(to==f) continue;
		dp[to]=dp[u]-val[to]+(vv-val[to]);
		dfs2(to,u); 
	}
}
int main()
{
   	cin>>n;
   	for(int i=1;i<=n;i++) cin>>a[i],vv+=a[i];
   	int x,y;
   	for(int i=1;i<n;i++)
   	{
   		cin>>x>>y;
		v[x].push_back(y);
		v[y].push_back(x);	
	}
	dfs1(1,0);
	ans=dp[1];
	dfs2(1,0);
	cout<<ans<<endl;
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值