• [ZJOI 2007] 时态同步


    [题目链接]

             https://www.lydsy.com/JudgeOnline/problem.php?id=1060

    [算法]

            贪心

            时间复杂度 : O(N)

    [代码]

          

    #include<bits/stdc++.h>
    using namespace std;
    #define MAXN 500010
    
    struct edge
    {
            int to,w,nxt;
    } e[MAXN << 1];
    
    int n,S,tot,cnt;
    int head[MAXN];
    long long ans;
    long long mx[MAXN];
    
    template <typename T> inline void read(T &x)
    {
        T f = 1; x = 0;
        char c = getchar();
        for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
        for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0';
        x *= f;
    }
    inline void addedge(int u,int v,int w)
    {
            tot++;
            e[tot] = (edge){v,w,head[u]};
            head[u] = tot;
    }
    inline void dfs(int u,int fa)
    {
            int son = 0;
            long long sum = 0;
            for (int i = head[u]; i; i = e[i].nxt)
            {
                    int v = e[i].to , w = e[i].w;
                    if (v == fa) continue;
                    dfs(v,u);    
                    son++;    
                    sum += (mx[v] + w);
                    mx[u] = max(mx[u],mx[v] + w);
            }        
            ans += son * mx[u] - sum;
    }
    
    int main() 
    {
            
            read(n); read(S);
            for (int i = 1; i < n; i++)
            {
                    int u , v , w;
                    read(u); read(v); read(w);
                    addedge(u,v,w);
                    addedge(v,u,w);
            }
            dfs(S,0);
            printf("%lld
    ",ans);
            
            return 0;
        
    }
  • 相关阅读:
    touchMove VS touchCancel
    svg viewbox 作用
    reactjs reactLink
    放开linux下的端口
    运算符重载函数作为类成员函数和友元函数 (转)
    MBean和MXBean 区别
    transfer-encoding
    CSRF
    vue知识拓展
    居中
  • 原文地址:https://www.cnblogs.com/evenbao/p/9615424.html
Copyright © 2020-2023  润新知