青蛙約會—-擴充歐幾裡得

來源:互聯網
上載者:User

題目:http://poj.org/problem?id=1061

總結:擴充歐幾裡得,ax+by=n,a和b可正可負,求出x可正可負。

求出特解x之後,求最小正整數解。剛剛一開始用的是b,結果WA了。後來發現ax/(a,b)+by/(a,b)=n/(a,b)。此時x+k*b/(a,b);

即設t=b/(a,b),t可能為負,所以要轉正,t=|t|,則x0=(x%b+b)%b,特解x可能為負;

如果你不用公式求最小解,而是用while(x>t){x-=t}    while(x<0){x+=t},的話,耗時比較多,此題此方法422ms,公式0ms。

資料大的話,很有可能逾時。

原始碼:

#include <stdio.h>typedef  long long ll;int x,y,m,n,L,s;ll p,q;int gcd(int a,int b){    if(b==0)  return a;    else    return gcd(b,a%b);}ll  extend_gcd(int a,int b,ll &x,ll &y){    ll t,ans;    if(b==0) {x=1; y=0; return a;}    else    {        ans=extend_gcd(b,a%b,x,y);        t=x;    x=y;  y=t-a/b*y;    }    return ans;}int main(){  scanf("%d %d %d %d %d",&x,&y,&m,&n,&L);   x=x%L;  y=y%L;   m=m%L; n=n%L;   s=gcd(m-n,L);   if((y-x)%s!=0)  { printf("Impossible\n");}   else   {       extend_gcd(m-n,L,p,q);       p=p*(y-x)/s;       L=L/s;       if(L<0)  L=-L;      printf("%d\n",(p%L+L)%L);   }}

聯繫我們

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