https://www.luogu.org/problem/P2606
不知道为什么这道题在数位dp里
分析;又是一个与排列有关的计数题,
P(i)>P(i/2)这个条件很重要啊
也有**P(2*i)>P(i)**,
也有**P(2*i+1)>P(i)**
像这种下标二倍的关系就要和二叉树考虑在一起
二叉树:i的左儿子就是2i,i的右儿子就是2i+1
而且这颗二叉树是个完全二叉树
首先计算出i个节点的完全二叉树中,
根节点的左子树包含的节点数l,右子树包含的节点数r。
首先,根节点的值必须为最小值。再考虑剩下的i-1个节点。
很容易想到,
可以在这i-1个节点中选出l个节点作为左子树,剩下的r个节点作为右子树。所以得出转移:
f[i]=C(i-1,l)×f[l]×f[r]
code by std(代码比较难看但真的很清晰):
#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;
}
原文地址:https://www.cnblogs.com/wzxbeliever/p/11664777.html
时间: 2024-10-16 09:44:10