【中国剩余定理】POJ 1006 & HDU 1370 Biorhythms

题目链接:

  http://poj.org/problem?id=1006

  http://acm.hdu.edu.cn/showproblem.php?pid=1370

题目大意

  (X+d)%23=a1,(X+d)%28=a2,(X+d)%33=a3,给定a1,a2,a3,d,求最小的X。

题目思路:

  【中国剩余定理】

  23,28,33互素,可以套中国剩余定理。

  也可以直接手算逆元。

  33×28×a模23的逆元为8,则33×28×8=5544;

  23×33×b模28的逆元为19,则23×33×19=14421; 

  23×28×c模33的逆元为2,  则23×28×2=1288。 

  因此有(5544×p+14421×e+1288×i)%lcm(23,28,33)=n+d (lcm(23,28,33)= 21252)

  所以n=(5544×p+14421×e+1288×i-d)%21252

  本题所求的是最小整数解,避免n为负,因此最后结果 n=(n+21252)% 21252

  so n=(5544*p+14421*e+1288*i-d+21252)%21252;

  

 1 //
 2 //by coolxxx
 3 //
 4 #include<iostream>
 5 #include<algorithm>
 6 #include<string>
 7 #include<iomanip>
 8 #include<memory.h>
 9 #include<time.h>
10 #include<stdio.h>
11 #include<stdlib.h>
12 #include<string.h>
13 //#include<stdbool.h>
14 #include<math.h>
15 #define min(a,b) ((a)<(b)?(a):(b))
16 #define max(a,b) ((a)>(b)?(a):(b))
17 #define abs(a) ((a)>0?(a):(-(a)))
18 #define lowbit(a) (a&(-a))
19 #define sqr(a) ((a)*(a))
20 #define swap(a,b) ((a)^=(b),(b)^=(a),(a)^=(b))
21 #define eps (1e-8)
22 #define J 10000000
23 #define MAX 0x7f7f7f7f
24 #define PI 3.1415926535897
25 #define N 4
26 using namespace std;
27 typedef long long LL;
28 int cas,cass;
29 int n,m,lll;
30 LL ans;
31 int p[N],a[N];
32 LL exgcd(LL a,LL b,LL &x,LL &y)
33 {
34     if(!b){x=1,y=0;return a;}
35     LL d=exgcd(b,a%b,y,x);
36     y-=a/b*x;
37     return d;
38 }
39 LL CRT(int nn)
40 {
41     LL sum=0,tot=1,tott,x,y;
42     int i;
43     for(i=1;i<=nn;i++)tot*=p[i];
44     for(i=1;i<=nn;i++)
45     {
46         tott=tot/p[i];
47         exgcd(tott,p[i],x,y);
48         x=(x%p[i]+p[i])%p[i];
49         sum=((sum+a[i]*tott%tot*x)%tot+tot)%tot;
50     }
51     return sum;
52 }
53 int main()
54 {
55     #ifndef ONLINE_JUDGE
56 //    freopen("1.txt","r",stdin);
57 //    freopen("2.txt","w",stdout);
58     #endif
59     int i,j,k,ii;
60 //    for(scanf("%d",&cas);cas;cas--)
61 //    for(scanf("%d",&cas),cass=1;cass<=cas;cass++)
62 //    while(~scanf("%s",s))
63     p[1]=23;p[2]=28;p[3]=33;
64     while(~scanf("%d",&n))
65     {
66         ans=0;
67         a[1]=n;
68         scanf("%d%d%d",&a[2],&a[3],&lll);
69         if(a[1]+a[2]+a[3]+lll==-4)break;
70         ans=CRT(3);
71         ans=(ans-lll+p[1]*p[2]*p[3]-1)%(p[1]*p[2]*p[3])+1;
72         printf("Case %d: the next triple peak occurs in %lld days.
",++cass,ans);
73     }
74     return 0;
75 }
76 /*
77 //
78 
79 //
80 */
千万不要点
原文地址:https://www.cnblogs.com/Coolxxx/p/5767742.html