<pre name="code" class="cpp">#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define ll long long
using namespace std;
//题意为:将不超过m个豆子放在n棵不同的树上,一共有多少种方法。
//用乘法逆元,乘法逆元两个周就忘没了,就是一个数m和p互质
//m的逆元就是m(p-2)因为m^(p-1)%p=1%p (费马小定理),有熟练了逆元
//看了烟大一大牛学长的博文,充满动力
ll fac[100002];
void getfac(ll p)//预处理阶层
{
fac[0]=1;
for(int i=1;i<=p;i++)
fac[i]=fac[i-1]*i%p;
}
ll qpow(ll a,ll b,ll p)//快速幂算法
{
ll ans=1;
while(b)
{
if(b&1)ans=ans*a%p;
a=a*a%p;
b/=2;
}
return ans;
}
ll lucas(ll n,ll m,ll p)
{
ll ans=1;
while(n&&m)
{
ll a=n%p;
ll b=m%p;
if(a<b) return 0;
ans=(ans*fac[a]*qpow(fac[b]*fac[a-b]%p,p-2,p))%p;
n/=p;
m/=p;
}
return ans;
}
int main(){
int t;
cin>>t;
while(t--)
{
ll n,m,p;
cin>>n>>m>>p;
getfac(p);
cout<<lucas(m+n,m,p)<<endl;
}
return 0;
}
Saving Beans (Lucas定理)
最新推荐文章于 2019-07-14 11:23:40 发布