1 条题解
-
0wz021001 LV 7 MOD @ 2021-02-05 21:28:10
#include<cstdio>
#include<cmath>
#define Rint register int
using namespace std;
typedef long long LL;
const int N = 1000003;
int n, head[N], to[N << 1], nxt[N << 1], w[N << 1];
inline void add(int a, int b, int c){
static int cnt = 0;
to[++ cnt] = b; nxt[cnt] = head[a]; head[a] = cnt; w[cnt] = c;
}
LL ans;
int siz[N];
inline void dfs(int x, int fa){
siz[x] = 1;
for(Rint i = head[x];i;i = nxt[i])
if(to[i] != fa){
dfs(to[i], x);
ans += (LL) abs(n - 2 * siz[to[i]]) * w[i];
siz[x] += siz[to[i]];
}
}
int main(){
scanf("%d", &n);
for(Rint i = 1;i < n;i ++){
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c); add(b, a, c);
}
dfs(1, 1);
printf("%lld", ans);
}
- 1