版权声明:本文为博主原创文章,转载请附上原博客链接。 https://blog.csdn.net/Dale_zero/article/details/82081986
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6446
在n个点的全排列中,考虑每一条边出现的次数。设这条边把树分为两个连通分量分别有M和N-M个节点。那么其排列数为M*(N-M),因为还有倒过来的情况所以要*2.考虑其他点的全排列,所以再乘上(n-2)!。所以这条边对答案的贡献为w*(N-M)*M*2*(n-2)!
遍历N-1条边,再乘上n-1,答案就为w*(N-M)*M*2*(n-1)!
#include<stdio.h>
#include<string.h>
#define inf 0x3f3f3f3f
#define mod 1000000007
#define For(i,m,n) for(int i=m;i<=n;i++)
#define Dor(i,m,n) for(int i=m;i>=n;i--)
#define LL long long
#define lan(a,b) memset(a,b,sizeof(a))
#define sqr(a) a*a
using namespace std;
const int maxn=100100;
const int maxnd=200100;
struct node
{
int to,next;
LL w;
};
int tot;
int head[maxn];
node bian[maxnd];
LL n;
LL po[maxn];
void init()
{
For(i,1,n)
head[i]=-1;
tot=0;
}
void addedge(int p,int q,int w)
{
bian[tot].to=q;
bian[tot].w=w;
bian[tot].next=head[p];
head[p]=tot++;
}
LL num[maxn];
LL ans=0;
void dfs(int s,int fa)
{
// printf("s=%d fa=%d\n",s,fa);
for(int j=head[s];j>=0;j=bian[j].next)
{
int to=bian[j].to;
LL w=bian[j].w;
if(to==fa)
{
num[s]++;
continue;
}
// printf("to=%d\n",to);
if(!num[to])
dfs(to,s);
num[s]+=num[to];
ans=(ans+w*(n-num[to])*num[to])%mod;
// printf("ans=%lld\n",ans);
}
}
int main()
{
po[0]=0;
po[1]=1;
for(LL i=2;i<=maxn-5;i++)
{
po[i]=(po[i-1]*i)%mod;
}
while(~scanf("%lld",&n))
{
if(n==1)
{
printf("0\n");
continue;
}
init();
lan(num,0);
ans=0;
For(i,1,n-1)
{
int p,q;
LL w;
scanf("%d%d%lld",&p,&q,&w);
addedge(p,q,w);
addedge(q,p,w);
}
dfs(1,0);
ans=(ans*po[n-1]*2)%mod;
printf("%lld\n",ans);
}
return 0;
}