[ZJOI2007] 时态同步

49 篇文章 0 订阅
42 篇文章 0 订阅

题目描述:

雾。

题目分析:

正解:树形DP
非正解:XJB DFS
记录maxtime[i]为以i为根的子树叶子节点距离i的最大时间
我们只需要用两次DFS即可求解答案

题目链接:

Luogu 1131
BZOJ 1060

Ac 代码:

#include <iostream>
#include <cstdio>
#define ll long long
const int maxm=510000;
ll maxtime[maxm],ans,cost[maxm<<1];
int head[maxm],to[maxm<<1],net[maxm<<1],cnt;
int n,root;
inline void addedge(int u,int v,ll c)
{
   cnt++;
   to[cnt]=v,cost[cnt]=c,net[cnt]=head[u],head[u]=cnt;  
}
void getdis(int now,int fa)
{
    for(int i=head[now];i;i=net[i])
    if(to[i]!=fa)
    {
        getdis(to[i],now);
        maxtime[now]=std::max(maxtime[now],cost[i]+maxtime[to[i]]);
    }
}
void getans(int now,int fa)
{
    for(int i=head[now];i;i=net[i])
    if(to[i]!=fa)
    {
        getans(to[i],now);
        ans+=(maxtime[now]-maxtime[to[i]]-cost[i]);
    }
}
int main()
{
    scanf("%d%d",&n,&root);
    for(int i=1;i<n;i++)
    {
        int u,v;
        ll c;
        scanf("%d%d%lld",&u,&v,&c);
        addedge(u,v,c);
        addedge(v,u,c);
    }
    getdis(root,0),getans(root,0);
    printf("%lld\n",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值