Code:
#include <bits/stdc++.h> #define setIO(s) freopen(s".in","r",stdin) #define maxn 500002 #define inf 1000000000000000 #define ll long long using namespace std; ll dis[maxn], s[maxn]; int hd[maxn], to[maxn << 1], nex[maxn << 1], val[maxn << 1], fa[maxn], chil[maxn]; int edges, n, root; ll maxv, ans; void add(int u, int v, int c) { nex[++edges] = hd[u], hd[u] = edges, to[edges] = v, val[edges] = c; } void dfs(int u, int ff) { fa[u] = ff, chil[u] = 0; for(int i = hd[u]; i ; i = nex[i]) { int v = to[i]; if(to[i] == ff) continue; ++chil[u]; dis[v] = dis[u] + (ll) val[i]; dfs(v, u); } } void dfs2(int u) { if(chil[u] == 0) { s[u] = maxv - dis[u]; return ; } ll _min = inf; for(int i = hd[u]; i ; i = nex[i]) { int v = to[i]; if(v == fa[u]) continue; dfs2(v); _min = min(_min, s[v]); } s[u] = _min; for(int i = hd[u]; i ; i = nex[i]) { int v = to[i]; if(v == fa[u]) continue; ans += s[v] - _min; } } int main() { // setIO("input"); scanf("%d%d",&n,&root); for(int i = 1, u, v, c; i < n ; ++i) { scanf("%d%d%d",&u,&v,&c); add(u, v, c), add(v, u, c); } dfs(root, 0); for(int i = 1; i <= n ; ++i) maxv = max(maxv, dis[i]); dfs2(root); printf("%lld\n",ans); return 0; }
BZOJ 1060: [ZJOI2007]时态同步 树上问题_贪心
原文:https://www.cnblogs.com/guangheli/p/10982708.html