题目传送门
代码:
#include<bits/stdc++.h>
using namespace std;typedef long long LL;
const int maxn=100000+100;
const LL mod=1e9+7;struct Edge{int to,next,len;
}edge[maxn<<1];
int head[maxn],son[maxn],tot;
LL sum;
int n;void DFS(int u,int fa){son[u]=1;for(int i=head[u];i!=-1;i=edge[i].next){Edge e=edge[i];int v=e.to;if(v==fa) continue;DFS(v,u);son[u]+=son[v]; sum=(sum+2LL*son[v]*(n-son[v])%mod*e.len%mod)%mod;}
}int main(){while(scanf("%d",&n)==1){for(int i=1;i<=n;i++) head[i]=-1;tot=0;for(int i=1;i<n;i++){int u,v,len;scanf("%d%d%d",&u,&v,&len);edge[tot].to=v;edge[tot].len=len;edge[tot].next=head[u];head[u]=tot++;edge[tot].to=u;edge[tot].len=len;edge[tot].next=head[v];head[v]=tot++;}sum=0;DFS(1,-1);for(int i=2;i<n;i++) sum=sum*i%mod;printf("%lld\n",sum);}
}