HDU 3579 模餘方程

來源:互聯網
上載者:User
/*HDU 3579不一定互質情況,神牛公式解析連結:http://yzmduncan.iteye.com/blog/1323599把推導過程翻譯成代碼即可... */

#include<iostream>#include<cstdio>#include<cmath>using namespace std;typedef long long ll;

ll gcd(ll a,ll b){    if(b==0) return a;    return gcd(b,a%b);}

ll kzgcd(ll a,ll b,ll&x,ll&y){    if(b==0) {        x=1, y=0;        return a;    }    ll d = kzgcd(b,a%b,x,y);    ll k = y;    y = x - a/b*y;    x = k;    return d;}

ll inv(ll a,ll b){ /// 求 a 的逆元 整數最小x    ll x,y;    ll k = kzgcd(a,b,x,y);     if(k!=1) return -1;    return (x%b+b)%b;}

bool merge(ll a1,ll n1,ll&a2,ll&n2){    ll d = gcd(n1,n2);    ll c = a2 - a1;    if(c%d) return false;    ll k = inv(n1/d,n2/d)*c/d;    ll a,n;    n = n1/d*n2;    a = (n1*k+a1)%(n1*n2/d);    a2 = a;    n2 = n;    return true;}

ll china_reminder(ll k,ll*a,ll*b){ /// 餘數,mod數     ll n1=b[1],a1=a[1];    for(ll i=2;i<=k;i++){        ll nn,aa;        nn = b[i], aa = a[i];        if(!merge(a1,n1,aa,nn))            return -1;        n1 = nn;        a1 = aa;    }     return (a1%n1+n1)%n1;}

int main(){     ll t,a[1110],b[1100];     int f;     cin>>f;     for(int ca=1;ca<=f;ca++){         cin>>t;         for(ll i=1;i<=t;i++)             cin>>b[i];         for(ll i=1;i<=t;i++)             cin>>a[i];         printf("Case %d: ",ca);         ll sum = china_reminder(t,a,b);         if(!sum){ /// 特判...             sum=1;             for(int i=1;i<=t;i++)                 sum = sum*b[i]/gcd(sum,b[i]);         }         printf("%lld\n",sum);     }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.