Tree and Permutation
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 0 Accepted Submission(s): 0
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个节点的树,边权为距离。
对于1-n的某一种排列p1,p2,p3……pn,贡献为dis(p1,p2)+dis(p2,p3)+dis(p3,p4)+……+dis(pn-1,pn)
求所有排列的贡献和
解析:观察整个式子,发现全排列后,每个dis(i , j)出现的次数相同,均为(n-1)!
具体推导:
对于一个n的全排列,会发现 任意x-y的边在这个全排列中出现的次数是一样的,(x-y和y—x是不一样的边)。也就是说我只需要计算出这个次数,然后再乘以所有边的总和(所有x-y和y-x的和)就可以了。
次数就是 ,(边的总数除以边的种类)化简一下就是 2*(n-1)!。
答案就是(n-1)!*sigma( dis(i , j) )
sigma( dis(i , j) )怎么求?
树上dfs一个个转移求即可。
代码实现:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=1e5+5;
const ll mod = 1e9+7;
struct node
{
int x,y,v,nxt;
}edge[maxn<<1];
ll head[maxn],cnt,n;
ll sz[maxn];
ll an;
int add(int x,int y,int v)
{
edge[cnt].x=x;
edge[cnt].y=y;
edge[cnt].v=v;
edge[cnt].nxt=head[x];
head[x]=cnt++;
}
int dfs(int root,int fa)
{
sz[root]=1;
for(int i=head[root]; i!=-1; i=edge[i].nxt)
{
int a=edge[i].y;
int b=edge[i].v;
// cout<<fa<<" "<<root<<" "<<a<<" "<<sz[root]<<endl;
if(a==fa) continue;
dfs(a,root);
sz[root] += sz[a];
an = ( an + (n-sz[a])%mod * sz[a]%mod * b%mod )%mod; //计算权值和
}
}
ll fac[maxn];
int main()
{
while(~scanf("%d",&n))
{
fac[0]=1;
for(int i=1;i<=maxn;i++)
fac[i]=(fac[i-1]*i)%mod;//阶乘取余打表
an=0;
memset(head,-1,sizeof(head));
memset(sz,0,sizeof(sz));
cnt=0;
for(int i=1;i<=n-1;i++)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
add(x,y,z);
add(y,x,z);
}
dfs(1,-1);
//i-j的所有和
printf("%lld\n",(ll)(2*an%mod*fac[n-1]%mod)%mod);
//i-j和j-i不一样*2
}
}