//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;
}
暑末 Day2 T3
最新推荐文章于 2021-09-08 18:44:44 发布