[ZJOI2007] 时态同步

记录一下叶子节点到根节点的距离 f[i] ,
通过一遍 dfs 找出每一个节点中子树修改的最小值 opt[i] ,
然后再用一遍 dfs 把标记下传,最后加一遍就可以了
ps:可能只有我用了三遍 dfs
我还是太菜了

#include <cstdio>

using namespace std;

template <class T>T Max(const T &a, const T &b) {return a > b ? a : b;}
template <class T>T Min(const T &a, const T &b) {return a < b ? a : b;}

typedef long long LL;

const int SN = 500000 + 10;
const int inf = 0x3f3f3f3f;

LL f[SN], head[SN], n, root, opt[SN], num, u, v, w, maxn[SN], ans[SN], maxx, res;

struct Edge {
    int u,v,next;LL w;
}E[SN<<1];

void Read(LL &x) {
    LL in = 0,f = 1;char ch = getchar();
    while(ch<'0' || ch>'9') {if(ch=='-') f = -1; ch = getchar();}
    while(ch>='0' && ch<='9') {in = in*10+ch-'0';ch = getchar();}
    x = in*f;
}

void Add(int u,int v,LL w) {
    E[++num].u = u;
    E[num].v = v;
    E[num].w = w;
    E[num].next = head[u];
    head[u] = num;
}

void dfs1(int u,int fa) {
    for(int i = head[u]; i; i = E[i].next) {
        int to = E[i].v;
        if(to == fa)    continue;
        f[to] = f[u] + E[i].w;maxx = Max(maxx, f[to]);
        dfs1(to,u);
    }
}

void dfs2(int u,int fa) {
    int cnt = 0;LL minn = inf;
    for(int i = head[u]; i; i = E[i].next) {
        int to = E[i].v;
        if(to == fa)    continue;cnt++; 
        dfs2(to,u);
        minn = Min(minn, opt[to]);
    }
    if(cnt == 0) opt[u] = ans[u] = maxx - f[u];
    else opt[u] = ans[u] = minn;
}

void dfs3(int u,int fa) {
    bool flag = 0;
    for(int i = head[u]; i; i = E[i].next) {
        int to = E[i].v;
        if(to == fa)    continue;
        ans[to] -= opt[u];flag = 1;
        dfs3(to,u);
    }
}

int main() {
    Read(n),Read(root);
    for(int i = 1; i < n; i++)  {
        Read(u),Read(v),Read(w);
        Add(u,v,w),Add(v,u,w);
    }

    dfs1(root,0);
    dfs2(root,0);   
    dfs3(root,0);
    for(int i = 1; i <= n; i++)  res+=ans[i];
    printf("%lld\n",res);
    return 0;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值