据说dfs会爆栈,写一个 BFS 序更新就好了~
#include <bits/stdc++.h>
#define N 1000005
#define ll long long
#define setIO(s) freopen(s".in","r",stdin)
using namespace std;
queue<int>q;
int edges,hd[N],to[N<<1],nex[N<<1],val[N<<1],fa[N],dfn[N],vis[N],size[N],cc[N];
void add(int u,int v,int c)
{
nex[++edges]=hd[u],hd[u]=edges,to[edges]=v,val[edges]=c;
}
int main()
{
// setIO("input");
int n,i,j,cnt=0;
scanf("%d",&n);
for(i=1;i<n;++i)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(a,b,c),add(b,a,c);
}
dfn[++cnt]=1;
vis[1]=1;
q.push(1);
for(;!q.empty();)
{
int u=q.front();q.pop();
size[u]=1;
for(int i=hd[u];i;i=nex[i])
{
int v=to[i];
if(vis[v]) continue;
vis[v]=1;
dfn[++cnt]=v;
q.push(v);
fa[v]=u;
cc[v]=val[i];
}
}
ll ans=0;
for(int i=cnt;i>=2;--i)
{
int v=dfn[i];
int u=fa[v];
size[u]+=size[v];
ans+=1ll*abs(n-size[v]-size[v])*cc[v];
}
printf("%lld\n",ans);
return 0;
}