FZU 2020 组合 [ Lucas ]

该博客讨论如何在大数情况下快速计算组合数C(n,m)模素数p的值。通过应用Lucas定理和费马小定理,可以有效地求解C(n,m) mod p,特别是在p为素数时。文章提供了样例输入和输出,并指出当n 摘要由CSDN通过智能技术生成

组合
Time Limit: 1000MS
Memory Limit: 32768KB
64bit IO Format: %I64d & %I64u

Description
给出组合数C(n,m), 表示从n个元素中选出m个元素的方案数。例如C(5,2) = 10, C(4,2) = 6.可是当n,m比较大的时候,C(n,m)很大!于是xiaobo希望你输出 C(n,m) mod p的值!

Input
输入数据第一行是一个正整数T,表示数据组数 (T <= 100) 接下来是T组数据,每组数据有3个正整数 n, m, p (1 <= m <= n <= 10^9, m <= 10^4, m < p < 10^9, p是素数)

Output
对于每组数据,输出一个正整数,表示C(n,m) mod p的结果。

Sample Input
2
5 2 3
5 2 61

Sample Output
1
10


就是求较大的组合数,用杨辉三角一定会爆
又p是素数,可以用Lucas定理, 并用费马小定理求逆元
注意在求C(n,m) 时, n < m 返回 0
并且如果 n,m 较小时可以预处理阶乘来提高速度

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<string>
#include<iomanip>
#include<ctime>
#include<climits>
#include<cctype>
#include<algorithm>
#ifdef WIN32
#define AUTO "%I64d"
#else
#define AUTO "%lld"
#endif
using namespace std;
#define smax(x,tmp) x=max((x),(tmp))
#define smin(x,tmp) x=min((x),(tmp))
#define maxx(x1,x2,x3) max(max(x1,x2),x3)
#define minn(x1,x2,x3) min(min(x1,x2),x3)
const int INF=0x3f3f3f3f;
typedef long long LL;
LL quick_mod(LL a,LL p,LL mod)
{
    if(p == 0) return 1;
    if(p == 1) return a % mod;
    LL tmp = quick_mod(a,p/2,mod);
    if(p & 1ll) return tmp * tmp % mod * a % mod;
    else return tmp * tmp % mod;
}
LL C(LL n,LL m,LL mod)
{
    if(n < m) return 0ll;
    if(m > (n>>1)) m = n - m;
    if(m == 0) return 1ll;
    LL ans = 1ll;
    for(int i=1;i<=m;i++)
    {
        LL a = (n - i + 1) % mod;
        LL b = i % mod;
        ans = ans * (a * quick_mod(b,mod-2,mod) % mod) % mod;
    }
    return ans;
}
LL Lucas(LL n,LL m,LL mod)
{
    if(m == 0ll) return 1ll;
    return C(n%mod,m%mod,mod) * Lucas(n/mod,m/mod,mod) % mod;
}
int main()
{
    freopen("lucas.in","r",stdin);
    freopen("lucas.out","w",stdout);
    int q;
    scanf("%d",&q);
    while(q--)
    {
        LL n,m,p;
        scanf(AUTO AUTO AUTO,&n,&m,&p);
        printf(AUTO"\n",Lucas(n,m,p));
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值