【bzoj2111】[ZJOI2010]Perm 排列计数

题目的意思就是有多少个大小为n的小根堆
这步转化太神了
f[i]表示用1~i的排列组成的小根堆有多少个

f[n]=C(size[left],n-1)*f[left]*f[right]


#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<iostream>
#define maxn 1000100

using namespace std;

long long fac[maxn],inv[maxn];
int n,p;
int size[maxn];
long long f[maxn];

long long power(long long x,int y)
{
	long long ans=1;
	while (y)
	{
		if (y&1) ans=ans*x%p;
		x=x*x%p;
		y>>=1;
	}
	return ans;
}

long long C(int x,int y)
{
	if (x>y) return 0;
	if (x<p && y<p) return (long long)(fac[y]*inv[y-x]%p)*inv[x]%p;
	return C(x%p,y%p)*C(x/p,y/p)%p;
}

int main()
{
	scanf("%d%d",&n,&p);
	int mx=min(n,p-1);
	fac[0]=1;
	for (int i=1;i<=mx;i++) fac[i]=(long long)fac[i-1]*i%p;
	inv[mx]=power(fac[mx],p-2);
	for (int i=mx-1;i>=0;i--) inv[i]=(long long)inv[i+1]*(i+1)%p;
	for (int i=n;i>=1;i--)
	{
		size[i]=1;if (i*2<=n) size[i]+=size[i*2];if (i*2+1<=n) size[i]+=size[i*2+1];
		if (i*2+1<=n) f[i]=(C(size[i*2],size[i]-1)*f[i*2]%p)*f[i*2+1]%p;
		else if (i*2<=n) f[i]=f[i*2];
		else f[i]=1;
	}
	printf("%lld\n",f[1]);
	return 0;
}


你可能感兴趣的:(【bzoj2111】[ZJOI2010]Perm 排列计数)