HDU6446 Tree and Permutation

dfs

考虑任意两点在全排列中的位置,发现有n-1种,而另外n-2个点的位置有(n-2)!种。

然后两点位置可兑换,所以任意两点的贡献为Lengh * 2 * (n-1) * (n-2)!

问题就变成了求树上任意两点的距离,由于题目求的答案是我们所有点的贡献之和,所以我们只需要求出任意两点的距离和即可,可以转换成求每条边的贡献,每条边的贡献相当于这条边左边的节点数 * 右边的节点数 * 边权。

所以dfs一次求边贡献就好了。

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define full(a, b) memset(a, b, sizeof a)
#define FAST_IO ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
inline int read(){
    int ret = 0, w = 0; char ch = 0;
    while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
    while(isdigit(ch)) ret = (ret << 3) + (ret << 1) + (ch ^ 48), ch = getchar();
    return w ? -ret : ret;
}
inline int gcd(int a, int b){ return b ? gcd(b, a % b) : a; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template <typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template <typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template <typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
    A ans = 1;
    for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
    return ans;
}
const int N = 200005;
const int MOD = 1e9 + 7;
int n, cnt, head[N], size[N], w[N<<1];
struct Edge { int v, next, val;} edge[N<<1];
vector<ll> ver;
void addEdge(int a, int b, int c){
    edge[cnt].v = b, edge[cnt].val = c, edge[cnt].next = head[a], head[a] = cnt ++;
}

void dfs(int s, int fa){
    size[s] = 1;
    for(int i = head[s]; i != -1; i = edge[i].next){
        int u = edge[i].v;
        if(u == fa) continue;
        w[u] = edge[i].val;
        dfs(u, s);
        size[s] += size[u];
    }
    ver.push_back(1LL * size[s] * (n - size[s]) % MOD * w[s] % MOD);
}

int main(){

    while(~scanf("%d", &n)){
        full(head, -1), full(w, 0), full(size, 0), cnt = 0; 
        ver.clear();
        for(int i = 1; i <= n - 1; i ++){
            int u = read(), v = read(), l = read();
            addEdge(u, v, l), addEdge(v, u, l);
        }
        w[1] = 0, dfs(1, 0);
        ll ans = 0;
        for(int i = 0; i < ver.size(); i ++){
            ans = (ans % MOD + ver[i] % MOD) % MOD;
        }
        for(int i = 1; i <= n - 1; i ++){
            ans = ans * i % MOD;
        }
        printf("%lld
", (ans << 1) % MOD);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/onionQAQ/p/11179659.html