记录size
dfs 乱搞
有人说貌似是树形dp
#include <cstring>
#include <cstdio>
#define LL long long
#define lp(i,j,k) for(int i = j;i <= k;++i)
LL abs (LL a) {
if(a <= 0)
return -a;
return a;
}
int read () {
int re = 0;
char c = getchar();
while(c < '0' || c > '9')
c = getchar();
while(c <= '9' && c >= '0') {
re = re * 10 + c - '0';
c = getchar();
}
return re;
}
int n,U,V,W;
LL ans;
struct edge {
int v,next,w;
}e[2000010];
int cnt,head[1000010],depth[1000010],sz[1000010];
void adde (int u,int v,int w) {
e[++cnt].v = v;
e[cnt].w = w;
e[cnt].next = head[u];
head[u] = cnt;
e[++cnt].v = u;
e[cnt].w = w;
e[cnt].next = head[v];
head[v] = cnt;
}
void dfs (int u,int I) {
for(int i = head[u];i != -1;i = e[i].next) {
int v = e[i].v;
if(!depth[v]) {
depth[v] = depth[u] + 1;
dfs(v,i);
sz[u] += sz[v];
}
}
sz[u]++;
ans += (LL)e[I].w * abs((LL)(n - sz[u] - sz[u]));
}
int main () {
memset(head,-1,sizeof head);
n = read();
lp(i,1,n - 1) {
U = read();
V = read();
W = read();
adde(U,V,W);
}
depth[1] = 1;
dfs(1,0);
printf("%lld\n",ans);
}