http://www.lydsy.com/JudgeOnline/problemset.php
注意到时间只能增加。
设dp[x]表示以x为根的子树中,到叶节点路径长度的最大值。
那么dp[x] = max{dp[v] + w}。
答案为∑dp[x] - (dp[v] + w)。
/* Footprints In The Blood Soaked Snow */
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long LL;
const int maxn = 500005;
int n, head[maxn], cnt, rt;
LL ans, dp[maxn];
struct _edge {
int v, w, next;
} g[maxn << 1];
inline void add(int u, int v, int w) {
g[cnt] = (_edge){v, w, head[u]};
head[u] = cnt++;
}
inline int iread() {
int f = 1, x = 0; char ch = getchar();
for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
return f * x;
}
inline void dfs(int x, int f) {
for(int i = head[x]; ~i; i = g[i].next) if(g[i].v ^ f) {
dfs(g[i].v, x);
dp[x] = max(dp[x], dp[g[i].v] + g[i].w);
}
for(int i = head[x]; ~i; i = g[i].next) if(g[i].v ^ f)
ans += dp[x] - dp[g[i].v] - g[i].w;
}
int main() {
n = iread(); rt = iread();
for(int i = 1; i <= n; i++) head[i] = -1; cnt = 0;
for(int i = 1; i < n; i++) {
int u = iread(), v = iread(), w = iread();
add(u, v, w); add(v, u, w);
}
dfs(rt, 0);
printf("%lld\n", ans);
return 0;
}