hdu 5446 (中国剩余定理+Lucas定理)

题意: 

    给你三个数n, m, k

    第二行是k个数,p1,p2,p3...pk

    所有p的值不相同且p都是质数

    求C(n, m) % (p1*p2*p3*...*pk)的值

代码:

     

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define N 200005
#define LL long long
LL mul(LL n,LL m,LL p){
    LL res=0;
    while(m){
        if(m&1)res+=n;
        n = (n+n)%p;
        m>>=1;
        res%=p;
    }
    return res;
}
LL fact(LL n,LL p){
    LL res = 1;
    for(int i=1;i<=n;i++)res=res*i%p;
    return res;
}
void ex_gcd(LL a,LL b,LL &d,LL &x,LL &y){
    if(!b)x=1,y=0,d=a;
    else {
        ex_gcd(b,a%b,d,y,x);
        y-=x*(a/b);
    }
}
LL inv(LL t,LL p){
    LL d,x,y;
    ex_gcd(t,p,d,x,y);
    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,res=0;
    for(int i=0;i<n;i++)M*=m[i];
    for(int i=0;i<n;i++){
        LL w = M/m[i];
        res = (res + mul(w*inv(w,m[i]),a[i],M))%M;
    }
    return res;
}
int main(){
    LL T,k;
    LL n,m,p[15],r[15];
    scanf("%lld",&T);
    while(T--){
        scanf("%lld%lld%lld",&n,&m,&k);
        for(int i=0;i<k;i++){
            scanf("%lld",&p[i]);
            r[i]=Lucas(n,m,p[i]);
            //printf("---\n");
            //printf("--%lld\n",r[i]);
        }
        printf("%lld\n",China(k,r,p));
    }
}


猜你喜欢

转载自blog.csdn.net/lj130lj/article/details/79660441