题意:求
1
到
这里建立
DP
模型:
f[i]
表示
i
个不同的数的所有排列中满足小根堆性质的排列的个数。
对于转移,首先计算出
首先,根节点的值必须为最小值。再考虑剩下的
i−1
个节点。很容易想到,可以在这
i−1
个节点中选出
l
个节点作为左子树,剩下的
f[i]=Cli−1∗f[l]∗f[r]
。
同时注意坑点:
n
可以大于
代码:
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
inline int read() {
int res = 0; bool bo = 0; char c;
while (((c = getchar()) < '0' || c > '9') && c != '-');
if (c == '-') bo = 1; else res = c - 48;
while ((c = getchar()) >= '0' && c <= '9')
res = (res << 3) + (res << 1) + (c - 48);
return bo ? ~res + 1 : res;
}
const int N = 1e6 + 5;
int n, PYZ, f[N], fac[N], Log[N], inv[N];
int qpow(int a, int b) {
int res = 1;
while (b) {
if (b & 1) res = 1ll * res * a % PYZ;
a = 1ll * a * a % PYZ;
b >>= 1;
}
return res;
}
int C(int x, int y) {
if (!y) return 1;
int u = C(x / PYZ, y / PYZ), v = x % PYZ, w = y % PYZ, z;
if (v < w) z = 0;
else z = 1ll * (1ll * fac[v] * inv[w] % PYZ) * inv[v - w] % PYZ;
return 1ll * u * z % PYZ;
}
int main() {
int i, kx, l = 1, r = 1; n = read(); PYZ = read();
fac[0] = 1; Log[0] = -1;
for (i = 1; i <= n; i++) fac[i] = 1ll * fac[i - 1] * i % PYZ,
Log[i] = Log[i >> 1] + 1;
kx = min(PYZ - 1, n); inv[kx] = qpow(fac[kx], PYZ - 2);
for (i = kx - 1; i >= 0; i--) inv[i] = 1ll * inv[i + 1] * (i + 1) % PYZ;
f[1] = f[2] = 1; f[3] = 2;
for (i = 4; i <= n; i++) {
if (i - (1 << Log[i]) + 1 <= (1 << Log[i] - 1)) l++;
else r++;
f[i] = 1ll * (1ll * C(i - 1, l) * f[l] % PYZ) * f[r] % PYZ;
}
printf("%d\n", f[n]);
return 0;
}