暑末 Day2 T3

6 篇文章 0 订阅
5 篇文章 0 订阅
//maxd表示根到叶子的最大距离
//预处理maxd,即知需修改的长度 
//to != fa 
#include<bits/stdc++.h>
using namespace std;
const int maxn = 500000;////
const int inf = 0x3f3f3f3f;
int n, tot, ans;
int st[maxn], out[maxn], dep[maxn], maxd[maxn], dp[maxn];
struct node{
    int v, w, nxt;
} edge[maxn*2];

inline int read(){
    int num = 0;
    char c;
    bool flag = 0;
    while((c = getchar()) == ' ' || c == '\r' || c == '\n');
    num = num + c - '0';
    while(isdigit(c = getchar()))   num = num*10 + c - '0';
    return num;
}

inline void in(int x, int y, int z){
    edge[++tot].v = y;
    edge[tot].w = z;
    edge[tot].nxt = st[x];
    st[x] = tot;
}

void DFS(int now, int fa){
    if(dp[now]) return;
    if(out[now] == 1)   return;
    for(int i = st[now]; i; i = edge[i].nxt){
        int to = edge[i].v;
        if(to == fa)    continue;
        DFS(to, now);
        maxd[now] = max(maxd[now], maxd[to] + edge[i].w);
        /*if(out[to] == 1)  dp[now] += maxd[now] - edge[i].w;
        dp[now] += dp[to];*/
    }
    for(int i = st[now]; i; i = edge[i].nxt){
        int to = edge[i].v;
        if(to == fa)    continue;
        ans += maxd[now] - maxd[to] - edge[i].w;
    }
}

int main(){
    //freopen("fireworks.in", "r", stdin);
    //freopen("fireworks.out", "w", stdout);
    n = read();
    for(int i = 1, x, y, z; i < n; i++){
        x = read(); y = read(); z = read();
        in(x, y, z);
        in(y, x, z);
        out[x]++;
        out[y]++;
    }
    int cnt = 0;
    for(int i = 1; i <= n; i++)
        if(out[i] == 1) cnt++;
    if(cnt == 1){
        printf("0\n");
        return 0;
    }
    DFS(1, 0);
    printf("%d\n", ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值