hdu6446 Tree and Permutation【推公式+dfs】

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

 

【分析】

我们考虑一条边在所有排列中总共贡献的次数。对于一条边E,这条边将树分为了两个部分,设左边有M个点,则右边有N-M个点。我们考虑任意一种排列,a1,a2,...,aN   . 这一排列需要N次动作,对于其中一个动作ai-a(i+1)  ,该次动作会经过边E当且仅当这两个点在边E的两侧,所以这两个点有可能的组合是2*M*(N-M)  (2是因为两侧可以互换),那么剩余的N-2个点的组合是 (N-2)! 也就是说有2M(N-M)(N-2)!中情况这一动作会有贡献,那么总共有N-1次动作 在乘以N-1  所以一条边在所有排列的总贡献为2*M*(N-M)*(N-1)!   然后求出N-1条边的贡献加起来了。

需要DFS去求出每条边左边点的个数和右边点的个数。

【代码】

 1 #include 
 2 #include 
 3 #include 
 4 #include 
 5 #include 
 6 #include 
 7 #include 
 8 #include 
 9 #include 
10 #include 
11 #include 
12 #define  pi acos(-1.0)
13 #define  eps 1e-6
14 #define  fi first
15 #define  se second
16 #define  lson l,m,rt<<1
17 #define  rson m+1,r,rt<<1|1
18 #define  bug         printf("******\n")
19 #define  mem(a,b)    memset(a,b,sizeof(a))
20 #define  fuck(x)     cout<<"["<<"x="<

 

你可能感兴趣的:(dfs,推公式)