HDU6446 Tree and Permutation(2018CCPC网络赛,树形dp)

版权声明:欢迎转载~转载请注明出处! https://blog.csdn.net/riba2534/article/details/82467844

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 个节点的树,一棵树有 n 1 条边,每条边都有权值.

现在题目问,对于从1n的全排列,对于其中每一种排列,这个排列的权值是从这个排列的第一个点走最短路走到这个排列的最后一个点的路程,题目需要求出所有的排列的权值和。

首先,这是一个全排列,对于树上点任意两个点 u , v ,这两个点在全排列中相邻的组合数是 2 ( n 1 ) ! ,那么现在只需要求出任意两点相邻的距离和即可。已知 u , v 相邻,那么 u > v 这条边对答案贡献的权值就是 u 左边的点的个数* v 右边的点的个数。

所以我们最后要求的就是: 2 w s i z [ v ] ( n s i z [ v ] ) ( n 1 ) ! 的和,用树形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;
}

猜你喜欢

转载自blog.csdn.net/riba2534/article/details/82467844