Tree and Permutation HDU - 6446

题目大意:
给你一颗树,然后让你求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的贡献。

#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;
}
void init()
{
    fac[0]=1;
    fac[1]=1;
    for(int i=2;i<maxn;i++)
    {
        fac[i]=fac[i-1]*i % mod;
    }
}
int n;
void dfs(int u,int fa)
{
    //cout<<u<<" "<<fa<<endl;
    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);
        //cout<<dp[v]<<endl;
        dp[u]+=dp[v];
        ans= (ans + dp[v]*(n-dp[v])%mod*w%mod)%mod;
    }
}
int main()
{

    init();
    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);
            num[u]++; num[v]++;
            add(u,v,w);
            add(v,u,w);
        }
        ans=0;
        for(int i=1;i<=n;i++)
        {
            if(num[i]==1)
            {
                dfs(i,0); break;
            }
        }
        ans=ans*2%mod*fac[n-1]%mod;
        printf("%lld\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/CURRYWANG97/article/details/82055814
今日推荐