1. 程式人生 > >POJ 1006 Biorhythms | 中國剩余定理

POJ 1006 Biorhythms | 中國剩余定理

同時 include net day 要求 names amp -s string

題目:

人自出生起就有體力,情感和智力三個生理周期,分別為23,28和33天。一個周期內有一天為峰值,在這一天,人在對應的方面(體力,情感或智力)表現最好。

通常這三個周期的峰值不會是同一天。現在給出三個日期,分別對應於體力,情感,智力出現峰值的日期。

然後再給出一個起始日期,要求從這一天開始,算出最少再過多少天後三個峰值同時出現。


題解:中國剩余定理.參考了這篇博文.

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<cstring>
 4 using namespace std;
5 int p,e,i,d,t=1,cnt,a[5],m[5]; 6 int exgcd(int a,int b,int &x,int &y) 7 { 8 if (b==0) return x=1,y=0,a; 9 int r=exgcd(b,a%b,y,x); 10 y-=(a/b)*x; 11 return r; 12 } 13 int CRT(int a[],int m[],int n) 14 { 15 int M=1; 16 int ans=0; 17 for (int i=1;i<=n;i++) 18 M*=m[i];
19 for (int i=1;i<=n;i++) 20 { 21 int x,y; 22 int Mi=M/m[i]; 23 exgcd(Mi,m[i],x,y); 24 ans=(ans+Mi*x*a[i])%M; 25 } 26 if (ans<0) ans+=M; 27 return ans; 28 } 29 int main() 30 { 31 while (scanf("%d%d%d%d",&p,&e,&i,&d)!=EOF) 32 { 33 if (p==-1
&& e==-1 && i==-1 && d==-1) 34 break; 35 a[1]=p; 36 a[2]=e; 37 a[3]=i; 38 m[1]=23; 39 m[2]=28; 40 m[3]=33; 41 int ans=CRT(a,m,3); 42 if (ans<=d) 43 ans+=21252; 44 printf("Case %d: the next triple peak occurs in %d days.\n",++cnt,ans-d); 45 } 46 return 0; 47 }

POJ 1006 Biorhythms | 中國剩余定理