CRT用于求解一元线性同余方程组(模数互质),实际上模数不互质我们也可以解决,在之前的某篇文章里提过。如下
http://www.cnblogs.com/autsky-jadek/p/6596010.html
#include<cstdio> using namespace std; typedef long long ll; ll m[4],a[4],D,ans; 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); } } void CRT(int r){ ll M=1,Mi,x0,y0,d; ans=0; for(int i=1;i<=r;++i){ M*=m[i]; } for(int i=1;i<=r;++i){ Mi=M/m[i]; exgcd(Mi,m[i],d,x0,y0); ans=(ans+Mi*x0*a[i])%M; } if(ans<=D){ ans+=M; } } int main(){ // freopen("poj1006.in","r",stdin); int zu=0; m[1]=23; m[2]=28; m[3]=33; while(1){ ++zu; scanf("%lld%lld%lld%lld",&a[1],&a[2],&a[3],&D); if(a[1]==-1 && a[2]==-1 && a[3]==-1 && D==-1){ break; } CRT(3); printf("Case %d: the next triple peak occurs in %lld days.\n",zu,ans-D); } return 0; }
时间: 2024-10-06 00:17:12