隔了这么久再写一篇题解。
其他一切都和我上一篇一样,只是 可以利用预处理前 项解决,然后求逆用 也就是 实现,因为求逆有意义的部分全部都与 互质。
这样做的话,复杂度为 。
贴上代码:
#include<bits/stdc++.h>
#define Rep(i,a,b) for(register int i=(a);i<=(b);++i)
#define Repe(i,a,b) for(register int i=(a);i>=(b);--i)
#define mp make_pair
#define pb push_back
using namespace std;
template<typename T>inline void read(T&x)
{
T f=1;register char ch;x=0;
for(ch=getchar();!isdigit(ch);ch=getchar())if(ch=='-')f=-1;
for(;isdigit(ch);ch=getchar())x=x*10+(ch^48);
x*=f;
}
inline void file()
{
#ifndef ONLINE_JUDGE
freopen("a.in","r",stdin);
freopen("a.out","w",stdout);
#endif
}
const int MAXN=1e6+7;
typedef long long ll;
static ll n,m;
static int P;
inline void init(){read(n),read(m),read(P);}
static int fac[MAXN];
static int ans=-1;
static int pri[MAXN],pw[MAXN],tt;
void exgcd(int&x,int&y,int a,int b)
{
if(!b){x=1,y=0;return;}
exgcd(y,x,b,a%b);
y-=a/b*x;
}
inline int power(int u,int v,int md)
{
register int sm;
for(sm=1;v;v>>=1,u=(ll)u*u%md)if(v&1)
sm=(ll)sm*u%md;
return sm;
}
inline int getfac(ll u,int p,int pw)
{
if(u<=p)return fac[u];
return (ll)fac[u%pw]*power(fac[pw],u/pw%(pw/p*(p-1)),pw)%pw*getfac(u/p,p,pw)%pw;
}
inline int getans(ll n,ll m,int p,int pw)
{
fac[0]=1;
Rep(i,1,pw)fac[i]=i%p==0?fac[i-1]:(ll)fac[i-1]*i%pw;
int up=getfac(n,p,pw),dow=(ll)getfac(m,p,pw)*getfac(n-m,p,pw)%pw;
ll lefp=0ll,x=n;
while(x)lefp+=x/p,x/=p;
x=m;
while(x)lefp-=x/p,x/=p;
x=n-m;
while(x)lefp-=x/p,x/=p;
Rep(i,1,lefp)
{
up=(ll)up*p%pw;
if(!up)return 0;
}
return (ll)up*power(dow,pw/p*(p-1)-1,pw)%pw;
}
inline int CRT(int x,int y,int md1,int md2)
{
static int k1,k2;exgcd(k1,k2,md1,md2);
return ((ll)(k1+md1*md2)*(y-x+md1*md2)%(md1*md2)*md1+x)%(md1*md2);
}
inline void solve()
{
register int lm=sqrt(P)+1,x=P;
Rep(i,2,lm)if(x%i==0)
{
pri[++tt]=i,pw[tt]=1;
while(x%i==0)pw[tt]*=i,x/=i;
}
if(x>1)++tt,pri[tt]=pw[tt]=x;
ans=getans(n,m,pri[1],pw[1]);
static int ml=pw[1];
Rep(i,2,tt)
{
// cerr<<getans(n,m,pri[i],pw[i])<<endl;
ans=CRT(ans,getans(n,m,pri[i],pw[i]),ml,pw[i]),ml*=pw[i];
}
printf("%d\n",ans);
}
int main()
{
file();
init();
solve();
cerr<<1.0*clock()/CLOCKS_PER_SEC<<endl;
return 0;
}