[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\n",ans);
        
        return 0;
    
}

猜你喜欢

转载自www.cnblogs.com/evenbao/p/9615424.html
今日推荐