2018CCPC网络赛 Tree and Permutation(树上dfs + 组合数学)

Tree and Permutation

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 548    Accepted Submission(s): 187

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

Source

2018中国大学生程序设计竞赛 - 网络选拔赛

考虑每一条边被走了多少次,任意一条边把一棵树分成了两部分,其中一部分有M个点,只有横跨两部分的点才能经过这条边,横跨两部分的点共有N(N - M)对,每一对点可以颠倒一下,所以在乘以2,每一对点在n!中相邻的次数为(n-1)!次(捆绑插空法),所以每一条边贡献了2*N(N-M)*(n-1)!次,dfs统计子树的节点个数就可以了

#include 
using namespace std;
typedef long long ll;
const int MOD = 1e9 + 7;
const int MAXN = 100005;
struct node
{
    int v,w,next;
}e[2 * MAXN];
ll ans,fac;
int head[MAXN],cnt;
int n;
void addedge(int u,int v,int w)
{
    e[cnt].v = v;
    e[cnt].w = w;
    e[cnt].next = head[u];
    head[u] = cnt++;
}
void init()
{
    cnt = 0;
    memset(head,-1,sizeof(head));
}
int DFS(int u,int pre)
{
    int sz1 = 1;
    for(int i = head[u]; i != -1; i = e[i].next) {
        if(e[i].v == pre) continue;
        int sz2 = DFS(e[i].v,u);
        ans = (ans + (ll)sz2 * (n - sz2) % MOD * 2 * fac % MOD * e[i].w % MOD) % MOD;
        sz1 += sz2;
    }
    return sz1;
}
int main(void)
{
    int u,v,w;
    while(scanf("%d",&n) != EOF) {
        init();
        ans = 0;
        for(int i = 1; i <= n - 1; i++) {
            scanf("%d %d %d",&u,&v,&w);
            addedge(u,v,w);
            addedge(v,u,w);
        }
        fac = 1;
        for(int i = 1; i <= n - 1; i++) {
            fac = (fac * i) % MOD;
        }
        DFS(1,-1);
        printf("%lld\n",ans);
    }
    return 0;
}

 

你可能感兴趣的:(ACM-数学,ACM-图论)