【BZOJ5305】【LOJ2526】【HAOI2018】蘋果樹(組合計數)

Description

https://loj.ac/problem/2526


Solution

題目相當於求每一種方案中任意兩點距離之和,也就是求usz[u](nsz[u])\sum_u sz[u] * (n-sz[u])
我們枚舉一個點ii,枚舉一個sz[i]sz[i]
ii之後的nin-i個點中有sz[i]1sz[i]-1個在ii的子樹內,所以答案乘上(nis1)\binom{n-i}{s-1}
對於ii的子樹內,方案數爲sz[i]!sz[i]!
對於ii的子樹之外的部分,方案數爲i!×(i1)(i)(i+1)(nsz[i]1)=i(i1)(nsz[i]1)!i!\times (i-1)(i)(i+1)\dots (n-sz[i]-1)=i(i-1)(n-sz[i]-1)!

將上面的所有東西乘起來即可。


Code

/**************************************
 * Au: Hany01
 * Prob: BZOJ5305 HAOI2018 蘋果樹
 * Date: Sep 22nd, 2018
 * Email: [email protected]
**************************************/

#include<bits/stdc++.h>

using namespace std;

typedef long long LL;
typedef pair<int, int> PII;
typedef vector<int> VI;
#define File(a) freopen(a".in", "r", stdin), freopen(a".out", "w", stdout)
#define rep(i, j) for (register int i = 0, i##_end_ = j; i < i##_end_; ++ i)
#define For(i, j ,k) for (register int i = (j), i##_end_ = (k); i <= i##_end_; ++ i)
#define Fordown(i, j, k) for (register int i = (j), i##_end_ = (k); i >= i##_end_; -- i)
#define Set(a, b) memset(a, b, sizeof(a))
#define Cpy(a, b) memcpy(a, b, sizeof(a))
#define SZ(a) ((int)(a.size()))
#define ALL(a) a.begin(), a.end()
#define pb(a) push_back(a)
#define mp(a, b) make_pair(a, b)
#define x first
#define y second
#define INF (0x3f3f3f3f)
#define INF1 (2139062143)
#define y1 wozenmezhemecaia 
#ifdef hany01
#define debug(...) fprintf(stderr, __VA_ARGS__)
#else
#define debug(...)
#endif

template<typename T> inline bool chkmax(T &a, T b) { return a < b ? a = b, 1 : 0; }
template<typename T> inline bool chkmin(T &a, T b) { return b < a ? a = b, 1 : 0; }

inline int read() {
    register char c_; register int _, __;
    for (_ = 0, __ = 1, c_ = getchar(); !isdigit(c_); c_ = getchar()) if (c_ == '-')  __ = -1;
    for ( ; isdigit(c_); c_ = getchar()) _ = (_ << 1) + (_ << 3) + (c_ ^ 48);
    return _ * __;
}

const int maxn = 2005;

int n, MOD, fac[maxn], C[maxn][maxn], Ans;

int main()
{
#ifdef hany01
    File("bzoj5305");
#endif

    n = read(), MOD = read(), fac[0] = 1;
    For(i, 1, n) fac[i] = (LL)fac[i - 1] * i % MOD;
    For(i, 0, n) {
        C[i][0] = C[i][i] = 1;
        For(j, 1, i - 1) C[i][j] = (C[i][j] = C[i - 1][j] + C[i - 1][j - 1]) >= MOD ? C[i][j] - MOD : C[i][j];
    }

    For(i, 2, n) For(s, 1, n - i + 1)
        Ans = (Ans += (LL)fac[s] * C[n - i][s - 1] % MOD * s % MOD * fac[n - s] % MOD * i % MOD * (i - 1) % MOD) >= MOD ? Ans - MOD : Ans;
    printf("%d\n", Ans);

    return 0;
}
發佈了393 篇原創文章 · 獲贊 410 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章