HDU-6446 Tree and Permutation

计算所有的全排列的之和,那么考虑每条边对答案的贡献是多大,比如1---2---3---4这种情况。

2到3对答案的贡献就是所有经过2到3的情况,正着看那么就是1---3   2---3   1---4   2---4这四种情况,倒过来也可以。

总结一下,设一条边左边有a个点,右边有b个点,那么经过该边的情况就是a*b*2种情况。

全排列一下,将这边进行捆绑,也就是将两个点看作一个点,那么就有(n-1)!种全排列

所以每条边的贡献就是a*b*2*(n-1)!*该边权值。

ac代码;

#include<bits/stdc++.h>

using namespace std;

const int maxn=1e5+10;
const int mod=1e9+7;

typedef long long ll;

struct node{
    int v,w,next;
}p[maxn<<1];

int head[maxn<<1],cnt;
ll ans,fac;
int n;

inline void init(){
    memset(head,-1,sizeof(head));
    cnt=0;
    ans=0;
    fac=1;
}

void addedge(int u,int v,int w){
    p[++cnt].v=v;
    p[cnt].w=w;
    p[cnt].next=head[u];
    head[u]=cnt;
}

int dfs(int u,int pre){
    int sz1=1;
    for(int e=head[u];~e;e=p[e].next){
        if(p[e].v==pre) continue;
        int sz2=dfs(p[e].v,u);
        sz1+=sz2;
        ans=(ans+(ll)sz2*(ll)(n-sz2)%mod*fac%mod*2%mod*(ll)p[e].w%mod)%mod;
    }
    return sz1;
}

int main(){
    int u,v,w;
    while(scanf("%d",&n)!=EOF){
        init();
        for(int i=0;i<n-1;i++){
            scanf("%d%d%d",&u,&v,&w);
            addedge(u,v,w);
            addedge(v,u,w);
        }
        for(int i=1;i<=n-1;i++){
            fac=fac*i%mod;
        }
        dfs(1,-1);
        printf("%lld\n",ans);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40679299/article/details/82114795
今日推荐