Tree and PermutationTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1204 Accepted Submission(s): 439 Problem Description There are N vertices connected by N−1 edges, each edge has its own length.
Input There are 10 test cases at most.
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
Source |
原博主https://blog.csdn.net/CURRYWANG97/article/details/82055814
做了一些小改动,其实可以结构体写.....但是我懒就没有写
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <queue>
#include <vector>
#include <set>
#include <map>
using namespace std;
typedef long long ll;
const int maxn = 100000 + 10;
int a[maxn];
const ll mod = 1e9 + 7;
ll fac[maxn];
struct edge
{
int to,next;
ll w;
}e[maxn*2];
int head[maxn];
int tot;
int num[maxn];
ll dp[maxn];
ll ans;
void add(int u,int to,int w)
{
e[++tot].next=head[u];
e[tot].w=w;
e[tot].to=to;
head[u]=tot;
}
int n;
void dfs(int u,int fa)
{
dp[u]=1;
for(int i=head[u];i!=0;i=e[i].next)
{
int v=e[i].to;
ll w=e[i].w;
if(v==fa) continue;
dfs(v,u);
dp[u]+=dp[v];
ans= (ans + dp[v]*(n-dp[v])%mod*w%mod)%mod;
}
}
int main()
{
while(~scanf("%d",&n))
{
tot=0;
memset(head,0,sizeof(head));
memset(dp,0,sizeof(dp));
memset(num,0,sizeof(num));
for(int i=0;i<n-1;i++)
{
int u,v;
ll w;
scanf("%d%d%lld",&u,&v,&w);
add(u,v,w);
add(v,u,w);
}
ans=0;
dfs(1,0);
ll now=1;
for(int i=2;i<=n-1;i++)
{
now=now*i % mod;
}
ans=ans*2%mod*now%mod;
printf("%lld\n",ans);
}
return 0;
}