【HDU】Unknown Treasure(卢卡斯定理)(中国剩余定理)

探讨了在大规模数据下如何高效求解组合数取模问题,尤其当模数为多个素数乘积时,利用卢卡斯定理与快速乘法结合中国剩余定理(CRT)求解的方法。

http://acm.hdu.edu.cn/showproblem.php?pid=5446

 

Problem Description

On the way to the next secret treasure hiding place, the mathematician discovered a cave unknown to the map. The mathematician entered the cave because it is there. Somewhere deep in the cave, she found a treasure chest with a combination lock and some numbers on it. After quite a research, the mathematician found out that the correct combination to the lock would be obtained by calculating how many ways are there to pick m different apples among n of them and modulo it with M. M is the product of several different primes.

Input

On the first line there is an integer T(T≤20) representing the number of test cases.

Each test case starts with three integers n,m,k(1≤m≤n≤1018,1≤k≤10) on a line where k is the number of primes. Following on the next line are k different primes p1,...,pk. It is guaranteed that M=p1⋅p2⋅⋅⋅pk≤1018 and pi≤105 for every i∈{1,...,k}.

Output

For each test case output the correct combination on a line.

Sample Input

1 9 5 2 3 5

Sample Output

6

 

 题意:

求一个组合数取模,只不过这个模是素数的乘积,得我们自己算,并且题目给出是哪些素数

分析:

观察到数据范围较大,直接求组合数无法解决(会爆)。组合数取模可以直接用卢卡斯定理,观察数据范围可以看到模数太大,不好处理,可以想到是分别对素数取模,再用中国剩余定理求出同余式的被模数

#include<cstdio>
using namespace std;
typedef long long ll;
ll p[16],r[15];
ll mul(ll a,ll b,ll p)//快速乘
{
    ll ret=0;
    while(b)
    {
        if(b&1) ret=(ret+a)%p;
        a=(a+a)%p;
        b>>=1;
    }
    return ret;
}
ll fact(ll n,ll p)//数的阶乘
{
    ll ret=1;
    for(ll i=1;i<=n;i++) ret=ret*i%p;
    return ret;
}
void ex_gcd(ll a,ll b,ll &x,ll &y,ll &d)//扩展欧几里得
{
    if(!b){d=a,x=1,y=0;}
    else{
        ex_gcd(b,a%b,y,x,d);
        y-=x*(a/b);
    }
}
ll inv(ll t,ll p)//逆元
{
    ll d,x,y;
    ex_gcd(t,p,x,y,d);
    return d==1?(x%p+p)%p:-1;
}
ll comb(ll n,ll m,ll p)//组合数
{
    if(m<0||m>n) return 0;
    return fact(n,p)*inv(fact(m,p),p)%p*inv(fact(n-m,p),p)%p;
}
ll lucas(ll n,ll m,ll p)//卢卡斯求组合数
{
    return m?lucas(n/p,m/p,p) * comb(n%p,m%p,p)%p:1;
}
ll china(ll n,ll *a,ll *m)//中国剩余定理
{
    ll M=1,ret=0;
    for(ll i=0;i<n;i++) M*=m[i];//把模数乘起来
    for(ll i=0;i<n;i++){
        ll w=M/m[i];
        ret=(ret+mul(w*inv(w,m[i]),a[i],M))%M;
    }
    return (ret+M)%M;
}
int main()
{
    ll T,n,m,k;
    scanf("%lld",&T);
    while(T--)
    {
        scanf("%lld%lld%lld",&n,&m,&k);
        for(ll i=0;i<k;i++)
        {
            scanf("%lld",&p[i]);
            r[i]=lucas(n,m,p[i]);
        }
        ll ans=china(k,r,p);
        printf("%lld\n",ans);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值