CodeForces - 1084D The Fair Nut and the Best Path 树形dp

The Fair Nut is going to travel to the Tree Country, in which there are n cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city u and go by a simple path to city v

. He hasn't determined his way, so it's time to do it.

A filling station is located in every city. Because of strange law, Nut can buy only wi

liters of gasoline in the i

-th city. We can assume, that he has infinite money. Each road has a length, and as soon as Nut drives through this road, the amount of gasoline decreases by length. Of course, Nut can't choose a path, which consists of roads, where he runs out of gasoline. He can buy gasoline in every visited city, even in the first and the last.

A path can consist of only one vertex.

He also wants to find the maximum amount of gasoline that he can have at the end of the path. Help him: count it.

Input

The first line contains a single integer n

(1≤n≤3⋅105

) — the number of cities.

The second line contains n

integers w1,w2,…,wn (0≤wi≤109

) — the maximum amounts of liters of gasoline that Nut can buy in cities.

Each of the next n−1

lines describes road and contains three integers u, v, c (1≤u,v≤n, 1≤c≤109, u≠v), where u and v — cities that are connected by this road and c

 — its length.

It is guaranteed that graph of road connectivity is a tree.

Output

Print one number — the maximum amount of gasoline that he can have at the end of the path.

Examples

Input

3
1 3 3
1 2 2
1 3 2

Output

3

Input

5
6 3 2 5 0
1 2 10
2 3 3
2 4 1
1 5 1

Output

7

题意:到达一个点的到这个点的价值,经过一个边花费这个边的价值,求得到的最大价值

题解:dp[i] 保存从i 节点开始走向子节点得到的最大价值,每走一个子代更新一下 结果 和 dp[i] 即可

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=3e5+10;
#define pb push_back
#define mp make_pair 
vector<pair<ll,ll> > v[N];
int val[N],n;
ll dp[N];
ll ans;
void dfs(int u,int fa)
{
	dp[u]=val[u];
	ans=max(ans,dp[u]);
	for(int i=0;i<v[u].size();i++)
	{
		int to=v[u][i].first;
		if(to==fa) continue;
		dfs(to,u);
		ans=max(ans,dp[to]+dp[u]-v[u][i].second);
		dp[u]=max(dp[u],val[u]+dp[to]-v[u][i].second);
	}
}
int main()
{
	int x,y,z;
    scanf("%d",&n);
    for(int i=1;i<=n;i++) scanf("%d",&val[i]);
    for(int i=1;i<n;i++)
    {
    	scanf("%d%d%d",&x,&y,&z);
    	v[x].pb(mp(y,z));
    	v[y].pb(mp(x,z));
	}
	dfs(1,0);
	printf("%lld\n",ans);
	return 0;
}

.

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值