P3807 【模板】卢卡斯定理(组合数学)

35 篇文章 0 订阅

题目传送门

这种求组合数我们不一定能通过常规的组合数方法去求,因为有可能n,m会大于mod,这样我们求出来的组合数就会不正确,而卢卡斯定理就可以很好的解决这一问题。

由于能力限制,证明后续补上

因为题目保证p是质数,所以费马小定理求逆元方便些,如果不是质数就用exgcd或者欧拉定理。

代码:

#include<bits/stdc++.h>
#define endl '\n'
#define null NULL
#define ls p<<1
#define rs p<<1|1
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define ll long long
#define int long long
#define pii pair<int,int>
#define ull unsigned long long
#define all(x) x.begin(),x.end()
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ct cerr<<"Time elapsed:"<<1.0*clock()/CLOCKS_PER_SEC<<"s.\n";
char *fs,*ft,buf[1<<20];
#define gc() (fs==ft&&(ft=(fs=buf)+fread(buf,1,1<<20,stdin),fs==ft))?0:*fs++;
inline int read(){int x=0,f=1;char ch=gc();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=gc();}
return x*f;}
using namespace std;
const int N=1e5+5;
const int inf=0x3f3f3f3f;
//const int mod=1e9+7;
const double eps=1e-7;
const double PI=acos(-1);
int j[N],inv[N],n,m,mod;
ll qpow(ll a,ll b)
{
    ll res=1;
    while(b)
    {
        if(b&1)
            res=res*a%mod;
        a=a*a%mod;
        b>>=1;
    }
    return res;
}
ll c(ll m,ll n)
{
    if(m>n)
        return 0;
    return j[n]*qpow(j[m],mod-2)%mod*qpow(j[n-m],mod-2)%mod;
}
ll lucas(ll a,ll b)
{
    if(!a)
        return 1;
    return c(a%mod,b%mod)*lucas(a/mod,b/mod)%mod;
}
signed main()
{
    int t;
    cin>>t;
    while(t--)
    {
        cin>>n>>m>>mod;
        j[0]=1;
        for(int i=1;i<=mod;i++)
            j[i]=j[i-1]*i%mod;
        cout<<lucas(n,n+m)<<endl;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值