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!种序列中,所以得序列和,序列和定义为:A1,A2,A3……AN=A1A2+A2A3+…….An-1An
思路:
首先,对于题目给出的n-1条边,我们可以这样考虑,去掉这条边后,将树分成了两部分,一部分有M个节点,另一部分有(N-M)个节点,所以我们必须在这两块中任意选择一个节点才会进过这条边,所以,有N*M*2中选择,然后又N!个序列所以对于E这条边,一共又2*N*M*(N-1)!*L的贡献,然后dfs,进行一遍树形dp,但是dfs要注意从入度为0的点开始。
AC代码:
#include<stdio.h>
#include<iostream>
#include<vector>
#include<string.h>
#define mem(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long LL;
const int maxn = 1e5 + 10;
const int M =1e9 + 7;
LL dp[maxn], n, vis[maxn], ans, A[maxn], in[maxn];
struct Edge
{
int to, val;
Edge(int a, int b): to(a), val(b){}
Edge(){}
};
vector<Edge>t[maxn];
void dfs(int u)
{
vis[u] = 1;
dp[u] = 1;
for(int i = 0; i < t[u].size(); i++)
{
Edge v = t[u][i];
if(!vis[v.to])
{
dfs(v.to);
ans += LL(dp[v.to])*(n-dp[v.to])%M*v.val%M;
dp[u] += dp[v.to];
}
}
}
void init()
{
ans = 0;
for(int i = 0 ; i < maxn; i++)
{
t[i].clear();
}
mem(dp, 0);
mem(vis, 0);
mem(in, 0);
A[0] = 1;
for(int i = 1; i < maxn; i++)
{
A[i] = (A[i-1]*i)%M;
}
}
int main()
{
while(scanf("%d", &n) != EOF)
{
init();
for(int i = 1; i < n; i++)
{
int from, to, val;
scanf("%d %d %d", &from, &to, &val);
t[from].push_back(Edge(to, val));
in[to]++;
//t[to].push_back(Edge(from, val));
}
vis[1] = 1;
for(int i = 1; i <= n; i++)
{
if(in[i] == 0)
{
dfs(1);
break;
}
}
ans = ans*2%M*A[n-1]%M;
printf("%lld\n", ans);
}
return 0;
}