hdu5446(数论)

来源:互联网 发布:linux cpu 超过100 编辑:程序博客网 时间:2024/06/05 10:26

转载自:大神博客

学习资料:中国剩余定理    逆元    lucas定理

题目链接:hdu5446


题目大意:C(n,m)%(pi)pi小于105mn,以及答案都是1018


题目分析:先使用Lucas定理求出对于每个piC(n,m)%pi的值。 再使用中国剩余定理对模数和余数求解即可。

令 total=piX=Cmn%(pi)k=Cmn/total

那么Cmn=ktotal+X 
两边同对pi取模, 
Cmn%pi=(ktotal+X)%pi=X%pi

X%p1=Cmn%p1=Lucas(n,m,p1)X%p2=Cmn%p2=Lucas(n,m,p2)...X%pn=Cmn%pn=Lucas(n,m,pn)

那么对于后面的方程组,可以用中国剩余定理算出X,这就是最终答案。

代码:

#include <queue>#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>using namespace std;typedef long long LL;const int maxm=20;const int maxn=1e5+100;LL T,n,m,k;LL p[maxm],lucas[maxm],factor[maxn];//快速幂LL poww(LL a,LL k,LL p){    LL ans=1;    while(k)    {        if(k&1) ans=ans*a%p;        a=a*a%p;        k>>=1;    }    return ans;}//加速a*b%pLL poww_mul(LL a,LL b,LL p){    LL ans=0;    while(b)    {        if(b&1) ans=(ans+a)%p;        a=(a+a)%p;        b>>=1;    }    return ans;}//factor[i]:1*2*..*i的乘积void getfactor(LL p){    factor[0]=1;    for(int i=1;i<=p;i++){        factor[i]=(factor[i-1]*i)%p;    }}//扩展欧几里得void extend_gcd(LL a,LL b,LL& d,LL& x,LL& y){    if(!b){        d=a;x=1;y=0;    } else{        extend_gcd(b,a%b,d,y,x);        y-=x*(a/b);    }}//lucas定理LL Lucas(LL n,LL m,LL p){    LL ans=1;    while(n&&m)    {        LL a=n%p,b=m%p;        if(a<b) return 0;        ans=(ans*factor[a]%p)*poww(factor[b]*factor[a-b]%p,p-2,p)%p;        n=n/p;m=m/p;    }    return ans;}//中国剩余定理LL CRT(LL a[],LL p[],LL len){    LL x,y,gcd,M=1,ans=0;    for(int i=1;i<=len;i++) M*=p[i];    for(int i=1;i<=len;i++){        LL Mi=M/p[i];        extend_gcd(Mi,p[i],gcd,x,y);        x=(x+p[i])%p[i];        ans=(ans+poww_mul(poww_mul(x,Mi,M),a[i],M))%M;    }    return (ans+M)%M;}int main(){//    freopen("in.txt","r",stdin);    ios::sync_with_stdio(false);    for(cin>>T;T--;){        cin>>n>>m>>k;        for(int i=1;i<=k;i++){            cin>>p[i];            getfactor(p[i]);            lucas[i]=Lucas(n,m,p[i]);        }        LL ans=CRT(lucas,p,k);        cout<<ans<<endl;    }    return 0;}



原创粉丝点击