[BZOJ2111] [ZJOI2010]Perm 排列计数

20 23

16

HINT

$1\leq n\leq 10^6$

试题分析

#include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;

#define LL long long

LL x=0,f=1;char c=getchar();
for(;!isdigit(c);c=getchar()) if(c=='-') f=-1;
for(;isdigit(c);c=getchar()) x=x*10+c-'0';
return x*f;
}
const LL MAXN=1100001;
const LL INF=999999;

LL N,P; LL fac[MAXN+1];
LL c[MAXN+1];

inline LL Pow(LL a,LL b){
LL ans=1LL;
while(b){
if(b&1) ans=ans*a%P;
a=a*a%P; b>>=1;
} return ans;
}
inline LL Lucas(LL N,LL M){
if (M>N) return 0; if(M==N) return 1;
if (N<P&&M<P) return (fac[N]*Pow(fac[N-M],P-2)%P*Pow(fac[M],P-2)%P)%P;
else return Lucas(N/P,M/P)*Lucas(N%P,M%P)%P;
}
inline LL dp(LL k){
if(k==1) return 1; if(!k) return 1; --k;
LL l=1,r=19,cnt=0; while(l<=r){
LL mid=(l+r)>>1;
if(c[mid]<=k&&k-c[mid]>=c[mid-1]) cnt=mid,l=mid+1;
else r=mid-1;
}LL tmp=cnt-1; if(2*c[cnt]<=k) tmp++; LL L,R;
if(tmp==cnt-1) R=k-c[cnt],L=c[cnt]; else L=c[cnt]+k-2*c[cnt],R=k-L;
return Lucas(k,L)*dp(L)%P*dp(R)%P;
}

int main(){
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);