Problem Description
There are N vertices connected by N−1 edges, each edge has its own length.
The set { 1,2,3,…,N } contains a total of N! unique permutations, let’s say the i-th permutation is Pi and Pi,j is its j-th number.
For the i-th permutation, it can be a traverse sequence of the tree with N vertices, which means we can go from the Pi,1-th vertex to the Pi,2-th vertex by the shortest path, then go to the Pi,3-th vertex ( also by the shortest path ) , and so on. Finally we’ll reach the Pi,N-th vertex, let’s define the total distance of this route as D(Pi) , so please calculate the sum of D(Pi) for all N! permutations.
Input
There are 10 test cases at most.
The first line of each test case contains one integer N ( 1≤N≤105 ) .
For the next N−1 lines, each line contains three integer X, Y and L, which means there is an edge between X-th vertex and Y-th of length L ( 1≤X,Y≤N,1≤L≤109 ) .
Output
For each test case, print the answer module 109+7 in one line.
Sample Input
3 1 2 1 2 3 1 3 1 2 1 1 3 2
Sample Output
16 24
思维难点:考虑整体中更局部的段对答案的贡献+计数
不要考虑一共多少条路径,然后再去考虑每种路径的答案想加。换一个角度,考虑每个边对答案的贡献
考虑树上的一条边,然后考虑他可能出现在哪里。
我们知道全排列,每两个数之间都会有一条路径,一共n个点,一共会有(n-1)条路径
然后考虑 一条树边 假设端点为 u,v, 那么 u 可以有 u的子树种选择, v可以有n-sz[u] 种选择,我们还可以 交换u和v的位置,
所以还得*2,那么剩下的点(n-2)就可以随便放了, 所以就是(n-2)!,那么 (u,v)还有 (n-1)中选择,所以 这条边对答案的贡献就是
即
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
#define rep(i,a,b) for(int i=a;i<b;i++)
const int N=1e5+10;
const int mod=1e9+7;
int cnt;
struct Edge{
int u,v,nt;
LL w;
Edge(int _u=0,int _v=0,int _nt=0,LL _w=0){
u=_u,v=_v,nt=_nt,w=_w;
}
}edge[N*2];
int head[N*2];
void add_edge(int u,int v,LL w){
edge[cnt]=Edge(u,v,head[u],w);
head[u]=cnt++;
}
int sz[N];
void dfs(int now,int fa){
sz[now]=1;
for(int i=head[now];i!=-1;i=edge[i].nt){
Edge& e=edge[i];
if(e.v==fa)continue;
dfs(e.v,now);
sz[now]+=sz[e.v];
}
}
int F[N];
void init(){
F[0]=1;
for(int i=1;i<N;i++)F[i]=1LL*i*F[i-1]%mod;
}
int main(){
init();
int n;
while(scanf("%d",&n)==1){
cnt=0;
fill(head,head+2*n+5,-1);
fill(sz,sz+n+5,0);
rep(i,0,n-1){
int u,v;LL w;
scanf("%d %d %lld",&u,&v,&w);
add_edge(u,v,w);
add_edge(v,u,w);
}
dfs(1,-1);
// rep(i,1,n+1)printf("i:%d sz:%d\n",i,sz[i]);
LL ans=0;
for(int i=0;i<2*n;i+=2){
Edge& e=edge[i];
LL s1=sz[e.u],s2=sz[e.v];
if(s1<s2)swap(s1,s2);
s1=n-s2;
LL tmp=2LL*s1%mod*s2%mod*F[n-1]%mod*e.w%mod;
ans=(ans+tmp)%mod;
//printf("i:%d u:%d v:%d w:%lld ans:%lld s1:%lld s2:%lld\n",i,e.u,e.v,e.w,ans,s1,s2);
}
printf("%lld\n",ans);
}
return 0;
}