codeforces 1083 A. The Fair Nut and the Best Path(树形dp)(第一道div1题)(*1800)

https://codeforces.com/contest/1083/problem/A

题意:每个节点都有自己的价值,从一个节点走到另一个节点会消耗固定值,但也会得到这个节点的价值,问怎样走才能得到最大的价值。

思路:利用树形结构进行dp,初始化每个点的价值为自身价值,对于每个节点都判断更新它的值或者不更新,从底向上进行dfs递归,更新出最优ans,从一个节点到另一个节点的收益为(目标节点价值-路上消耗的价值)

感想:没法直接保存最优值的话,利用一个变量ans在更新过程中进行保存,树形dp万变不离其宗啊。。,

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
#define ll long long
#define mod 1000000007
#define inf 0x3f3f3f3f
using namespace std;
#define ll long long
using namespace std;
#define maxn 300005
ll a[maxn];
ll dp[maxn];
ll ans = 0;
vector<pair<int, ll> >v[maxn];
ll dfs(int cur, int fa)
{
    ans = max(ans, dp[cur]);
    for(int i = 0; i < v[cur].size(); i ++)
    {
        int son = v[cur][i].first;
        if(son == fa) continue;
        dfs(son, cur);
        ll val = dp[son] - v[cur][i].second;
        ans = max(ans, dp[cur] + val);
        dp[cur] = max(dp[cur], a[cur] + val);
    }
    return ans;
}
int main()
{
    int n;
    int u, vv, w;
    cin>>n;
    for(int i = 1; i <= n; i ++)
    {
        cin>>a[i];
        dp[i] = a[i];
    }
    for(int i = 1; i < n; i ++)
    {
        cin>>u>>vv>>w;
        v[u].push_back({vv, w});
        v[vv].push_back({u, w});
    }
    cout<<dfs(1, 0)<<endl;
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值