hdu5446Unknown Treasure

中国剩余定理的简单运用结合LUCAS定理
另外就是两个数相乘他的结果可能爆long long ,所以要用快速乘法进行计算

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll num;
ll num1[11];
ll num2[11];
ll fact[100005];

void init(ll p){
    fact[0]=1;
    for(int i=1;i<=p;i++)
        fact[i]=fact[i-1]*i%p;
}

ll quick_mod(ll n,ll m,ll p){
    ll ret=1;
    while(m>0){
        if(m%2==1)
            ret=ret*n%p;
        m=m>>1;
        n=n*n%p;
    }
    return ret;
}

ll Lucas(ll n,ll m,ll p){
    if(m==0)
        return 1;
    init(p);
    ll ret=1;
    while(n&&m){
        ll a=n%p;
        ll b=m%p;
        if(a<b) return 0;
        ret=ret*fact[a]*quick_mod(fact[b]*fact[a-b]%p,p-2,p)%p;
        n/=p;
        m/=p; } return ret; } //返回d=gcd(a,b);和对应于等式ax+by=d中的x,y ll extend_gcd(ll a,ll b,ll &x,ll &y){ if(a==0&&b==0) return -1; //无最大公约数 if(b==0){ x=1; y=0; return a; } ll d=extend_gcd(b,a%b,y,x); y-=a/b*x;
    return d;
}

//ax=1(mod n)
ll mod_reverse(ll a,ll n){
    ll x,y;
    ll d=extend_gcd(a,n,x,y);
    if(d==1)
        return (x%n+n)%n;
    else
        return -1;
}

ll mul(ll x,ll y,ll p){
    ll res=0;
    while(y){
        if(y&1){
            res+=x;
            res%=p;
        }
        x=(x<<1)%p;
        y=y>>1;
    }
    return res;
}

ll solve(ll k){
    ll n,m;
    ll res=0;
    for(int i=1;i<=k;i++){
        m=num/num1[i];
        n=mod_reverse(m,num1[i]);   //nm的逆元
        res=(res+mul(mul(m,n,num),num2[i],num))%num;  //快速乘法,本来会爆long long
    }
    return (res%num+num)%num;
}

int main(){
    int t;
    ll n,m,k;
    scanf("%d",&t);
    while(t--){
        scanf("%I64d%I64d%I64d",&n,&m,&k);
        num=1;
        for(int i=1;i<=k;i++){
            scanf("%I64d",&num1[i]);
            num*=num1[i];
            num2[i]=Lucas(n,m,num1[i]);
            //cout<<num2[i]<<"PPPP"<<endl;
        }
        printf("%I64d\n",solve(k));
    }
    return 0;
}
/*
100
9 5 2
3 5
*/

你可能感兴趣的:(hdu5446Unknown Treasure)