BZOJ1060

2 篇文章 0 订阅

传送门:BZOJ1060

有些意思的树形DP。

我只想到了用 f(i,j) 表示以i为根的子树的权值之和为j的最小花费,但我没有想到这个j居然是可以贪心从而藏进去的……

注意到有以下事实成立:在靠近根的节点使用技能更优秀。

于是贪心即可,我们维护每个结点与其子树中叶子结点的最大距离,然后枚举它的子结点,加上它的最大距离与它子结点的最大距离与该边权值之差即可。

比较坑的是,这题标程统计最大距离时忘开long long,统计答案时又开了long long……

最大距离应该开long long!不开long long 只是因为数据有误无法AC!

最大距离应该开long long!不开long long 只是因为数据有误无法AC!

最大距离应该开long long!不开long long 只是因为数据有误无法AC!

重要的事情说三遍。

代码上的小细节见下。

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

struct Edge{
    int from,to;
    int w;
    Edge(){
        from=to=0;
        w=0;
    }
    Edge(int from_,int to_,int w_){
        from=from_;
        to=to_;
        w=w_;
    }
};

vector<Edge> G[500005];
int maxn[500005];
int n;
int root;
long long ans;

void AddEdge(int from,int to,int w)
{
    G[from].push_back(Edge(from,to,w));
    G[to].push_back(Edge(to,from,w));
}
void Dfs(int root,int fa)
{
    for(int i=0;i<G[root].size();i++){
        Edge e=G[root][i];
        if(e.to==fa)
            continue;
        Dfs(e.to,root);
        maxn[root]=max(maxn[root],maxn[e.to]+e.w);
    }
    for(int i=0;i<G[root].size();i++){
        Edge e=G[root][i];
        if(e.to==fa)
            continue;
        ans+=maxn[root]-maxn[e.to]-e.w;
    }
}

void Readdata()
{
    freopen("loli.in","r",stdin);
    scanf("%d\n%d",&n,&root);
    for(int i=1;i<n;i++){
        int a,b,c;
        scanf("%d%d%d",&a,&b,&c);
        AddEdge(a,b,c);
    }
}

void Close()
{
    fclose(stdin);
    fclose(stdout);
}

int main()
{
    Readdata();
    Dfs(root,-1);
    cout<<ans;
    Close();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值