Tree and Permutation HDU - 6446(树形dp)

Tree and Permutation HDU - 6446

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

题意:

对于一个排列的权重,代表从 a1a2a2a3.... a 1 走 到 a 2 , a 2 走 到 a 3 . . . . 这样走下去的权重和,就是一个排列的权重,然后求全排列的权重和。。

分析:

首先先求出任意两点的距离的和,对于选取任意两点的距离之和的求法请看Average distance HDU - 2376
我们记为 ans a n s

因为这道题目和全排列有关系,对于任意的两点 xy,(n1)!×2 x y , 其 在 全 排 列 中 相 邻 的 组 合 数 是 ( n − 1 ) ! × 2

即将xy当做一个整体,然后内部两种方式即 xy,yx x → y , y → x

所以 ans=ans×2×(n1)! a n s = a n s × 2 × ( n − 1 ) !

code:

#include 
using namespace std;
typedef long long ll;
const int maxn = 1e5+10;
const ll mod = 1e9+7;
ll fac[maxn];
struct edge{
    int to,nxt;
    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].nxt = 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){
    dp[u] = 1;
    for(int i = head[u]; i != 0; i = e[i].nxt){
        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(){
    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;
}

你可能感兴趣的:(树形dp)