拓展中國剩餘定理(ex_crt)

來源:互聯網
上載者:User

標籤:def   gcd   printf   tps   模型   gif   col   queue   比較   

一般來講,crt(中國剩餘定理)比較常見,而ex_crt(拓展中國剩餘定理)不是很常用

但是noi 2018偏偏考了這麼個詭異的東西...

所以這裡寫一個ex_crt模板

模型:

求一個x滿足上述方程,其中a1,a2...an不一定互質

解法:

設存在一特解x0滿足前k個方程組,且LCM(a1,a2...ak)=M

則前k個方程的通解x=x0+k·M(k∈Z)

這是很顯然的,因為 (1<=i<=k)

那麼第k+1個方程等價於:求使的t

這顯然可以使用ex_gcd求解(移項即可)

那麼剩餘部分就簡單了:不斷維護一個x0,最後返回x0即可

#include <cstdio>#include <cmath>#include <cstring>#include <cstdlib>#include <iostream>#include <algorithm>#include <queue>#include <stack>#define ll long longusing namespace std;ll n;ll a[100005];ll b[100005];ll pow_add(ll x,ll y,ll mod){    ll ans=0;    while(y)    {        if(y%2)        {            ans+=x;            ans%=mod;        }        y/=2;        x+=x;        x%=mod;    }    return ans;}ll gcd(ll x,ll y){    if(y==0)    {        return x;    }    return gcd(y,x%y);}void ex_gcd(ll a,ll b,ll &x,ll &y){    if(b==0)    {        x=1;        y=0;        return;    }    ex_gcd(b,a%b,x,y);    ll t=x;    x=y;    y=t-(a/b)*x;}ll ex_crt(){    ll M0=a[1];    ll ans=b[1];    for(int i=2;i<=n;i++)    {        ll r=gcd(M0,a[i]);        ll bb=((b[i]-ans)%a[i]+a[i])%a[i];        if(bb%r)        {            return -1;        }        bb/=r;        ll M=M0/r;        ll aa=a[i]/r;        ll x,y;        ex_gcd(M,aa,x,y);        x=pow_add(x,bb,aa);        ans+=x*M0;        M0*=aa;        ans=(ans%M0+M0)%M0;    }    return (ans%M0+M0)%M0;}int main(){    scanf("%lld",&n);    for(int i=1;i<=n;i++)    {        scanf("%lld%lld",&a[i],&b[i]);    }    printf("%lld\n",ex_crt());    return 0;}

 

拓展中國剩餘定理(ex_crt)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.