【树的DFS】codeforces1084D The Fair Nut and the Best Path

D. The Fair Nut and the Best Path
time limit per test3 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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
inputCopy
3
1 3 3
1 2 2
1 3 2
outputCopy
3
inputCopy
5
6 3 2 5 0
1 2 10
2 3 3
2 4 1
1 5 1
outputCopy
7


 已经一个多月没打CF了,真的太忙了QwQ,今天VP了一场,发现自己反应速度有所下降了,好多简单题都WA了好几发,以后像这种快速思维的训练看来也不能落下了。
 最近一场之后,CF的Rank1居然不再是Tourist了,而是新人(据说才学编程5年…),仿佛是一个新的时代要来了吗?
 题目很简单,首先一条直线上的情况,很显然等价于最大连续和的问题。最大连续和有一个解法是求出前缀和,用每个位置以及之后的前缀和的max值,减去这个位置的前缀和,最大值就是答案。如果放在树上也是类似的,用val[i]表示从顶点到i点路径的总值,mv[i]表示第i个顶点子树上的val值的最大值,mv2[i]表示这个次大值。那么答案可以用mv2[x]+mv[x]-val[x]*2+w[x]来更新,枚举x就行了,可以理解成枚举答案路径的最高点。

#include<cstdio>
#include<vector>
using namespace std;
using LL=long long;

struct edge
{
	int to,c;
};

int n,w[300005];
LL val[300005],mv[300005],ans;
vector<edge> E[300005];

void dfs(int x, int fa)
{
	mv[x]=val[x];
	LL tmp=val[x];
	for(auto j:E[x])
		if(j.to!=fa)
		{
			val[j.to]=w[j.to]-j.c+val[x];
			dfs(j.to,x);
			if(mv[j.to]>=mv[x])
			{
				tmp=mv[x];
				mv[x]=mv[j.to];
			}
			else if(mv[j.to]>tmp)
				tmp=mv[j.to];
		}
	ans=max(ans,tmp+mv[x]-val[x]*2+w[x]);
}

int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
		scanf("%d",&w[i]);
	for(int i=1,u,v,c;i<n;i++)
	{
		scanf("%d%d%d",&u,&v,&c);
		E[u].push_back((edge){v,c});
		E[v].push_back((edge){u,c});
	}
	val[1]=w[1];
	dfs(1,0);
	printf("%lld",ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/BUAA_Alchemist/article/details/84963844