POJ.1006 Biorhythms (拓展欧几里得+中国剩余定理)
题意分析
不妨设日期为x,根据题意可以列出日期上的方程:
化简可得:
根据中国剩余定理求解即可。
代码总览
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
typedef int ll;
ll p,e,i,d;
void exgcd(ll a, ll b, ll& d, ll& x, ll &y)
{
if(!b){
d = a,x = 1,y = 0;
}else{
exgcd(b, a % b, d, y, x);
y -= x * (a / b);
}
}
int CRT(int a[], int m[])
{
int ans = 0;
int M = 1;
int x,y,gcd;
for(int i = 1; i<=3;++i)M*=m[i];
for(int i =1 ;i<=3;++i){
int Mi = M/m[i];
exgcd(Mi,m[i],gcd,x,y);
ans = (ans + Mi * a[i] * x) % M;
}
if(ans<=0) ans+=M;
if(ans<d) ans+=M;
return ans;
}
int main()
{
//freopen("in.txt","r",stdin);
int kase = 0;
while(scanf("%d %d %d %d",&p,&e,&i,&d)){
if(p == -1 && e == -1 && i == -1 && d == -1) break;
int a[] = {0,p,e,i};
int m[] = {0,23,28,33};
int ans = CRT(a,m);
printf("Case %d: the next triple peak occurs in %d days.\n",++kase,ans-d);
}
return 0;
}