HDU6446 Tree and Permutation(2018CCPC網絡賽,樹形dp)

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

思路

給出一個具有n 個節點的樹,一棵樹有n1 條邊,每條邊都有權值.

現在題目問,對於從1n的全排列,對於其中每一種排列,這個排列的權值是從這個排列的第一個點走最短路走到這個排列的最後一個點的路程,題目需要求出所有的排列的權值和。

首先,這是一個全排列,對於樹上點任意兩個點u,v ,這兩個點在全排列中相鄰的組合數是2(n1)! ,那麼現在只需要求出任意兩點相鄰的距離和即可。已知u,v 相鄰,那麼u>v 這條邊對答案貢獻的權值就是u 左邊的點的個數*v 右邊的點的個數。

所以我們最後要求的就是:2wsiz[v](nsiz[v])(n1)! 的和,用樹形dp可以解決

代碼

#include <bits/stdc++.h>
using namespace std;
#define mem(a, b) memset(a, b, sizeof(a))
typedef long long ll;
const ll N = 1e5 + 10;
const ll mod = 1e9 + 7;
ll first[N], tot, n, siz[N], fac[N], ans;
struct edge
{
    ll v, w, next;
} e[N * 2];
void add_edge(ll u, ll v, ll w)
{
    e[tot].v = v, e[tot].w = w;
    e[tot].next = first[u];
    first[u] = tot++;
}
void init()
{
    mem(first, -1);
    mem(siz, 0);
    tot = 0;
    ans = 0;
}

void dfs(ll u, ll fa)
{
    siz[u] = 1;
    for (ll i = first[u]; ~i; i = e[i].next)
    {
        ll v = e[i].v, w = e[i].w;
        if (v == fa)
            continue;
        dfs(v, u);
        siz[u] += siz[v];
        ans += siz[v] * (n - siz[v]) * w % mod;
        ans %= mod;
    }
}
void solve()
{
    init();
    ll u, v, w;
    for (ll i = 1; i <= n - 1; i++)
    {
        scanf("%lld%lld%lld", &u, &v, &w);
        add_edge(u, v, w);
        add_edge(v, u, w);
    }
    dfs(1, -1);
    printf("%lld\n", 2 * ans * fac[n - 1] % mod);
}
void pre_init()
{
    fac[1] = 1;
    for (ll i = 2; i < N; i++)
        fac[i] = i * fac[i - 1] % mod;
}
int main()
{
    //freopen("in.txt", "r", stdin);
    pre_init();
    while (~scanf("%lld", &n))
        solve();
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章