Codeforces 1083A

To a tree, each node, each side has the right values, will add weight to a corresponding, through a side edge of the weights is subtracted, asked from the node, right up to how much energy the rest value.
Tree dp, for a node u, and can not count its parent node, and its two count two (or more) of his son, unable to walk because of repeated path.
DP [u] u to represent the maximum residual value of its weight a leaf node.
dp [u] = max (val [u] + dp [v] - cost (u, v)) v u child is
updating the answer, we must first determine what if a node does not take the side of what constitutes the best if you can solution, then for u and sons v, u, and may have other children nodes form a single u better than a case in which a dp [u] + dp [v ] - cost (u, v) updating ans

#include <bits/stdc++.h>
#define f first
#define s second
using namespace std;
typedef pair<int,int> PII;
typedef long long LL;
const int N = 3e5 + 10;

int n,u,v,w,val[N];
vector<PII> G[N];
LL ans,dp[N];
void dfs(int u,int fa){
	dp[u] = (LL)val[u];
	ans = max(ans,dp[u]);
	for(int i = 0;i<G[u].size();i++){
		int v = G[u][i].f;
		if(v == fa) continue;
		dfs(v,u);
		ans = max(ans,dp[u] + dp[v] - G[u][i].s);
		dp[u] = max(dp[u],val[u] + dp[v] - G[u][i].s);
	}
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	cin>>n;
	for(int i = 1;i<=n;i++) cin>>val[i];
	for(int i = 0;i<n-1;i++){
		cin>>u>>v>>w;
		G[u].push_back({v,w});
		G[v].push_back({u,w});
	}
	dfs(1,-1);
	cout<<ans;
	return 0;
}

Guess you like

Origin blog.csdn.net/winhcc/article/details/89340725