poj 1006 Biorhythms (中国剩余定理模板题)

题目链接:

**题意:**人自出生起就有体力,情感和智力三个生理周期,分别为23,28和33天。一个周期内有一天为峰值,在这一

天,人在对应的方面(体力,情感或智力)表现最好。通常这三个周期的峰值不会是同一天。现在给出三个日

期,分别对应于体力,情感,智力出现峰值的日期。然后再给出一个起始日期,要求从这一天开始,算出最少

再过多少天后三个峰值同时出现。

思路:解一个线性同余方程。crt的模板题。

关于crt的讲解:中国剩余定理学习笔记

几年前就A过了,现在重新写题解复习一下。

/* ***********************************************
Author :111qqz
Created Time :Thu 13 Oct 2016 08:00:04 PM CST
File Name :code/poj/1006.cpp
************************************************ */
 1#include <cstdio>
 2#include <cstring>
 3#include <iostream>
 4#include <algorithm>
 5#include <vector>
 6#include <queue>
 7#include <set>
 8#include <map>
 9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
19#define pi pair < int ,int >
20#define MP make_pair
 1using namespace std;
 2const double eps = 1E-8;
 3const int dx4[4]={1,0,0,-1};
 4const int dy4[4]={0,-1,1,0};
 5const int inf = 0x3f3f3f3f;
 6int p,e,i,d;
 7int a[5],m[5];
 8void exgcd(int a,int b,int &x,int &y)
 9{
10    if (b==0)
11    {
12	x = 1;
13	y = 0;
14	return;
15    }
16    exgcd(b,a%b,x,y);
17    int tmp = x;
18    x = y;
19    y = tmp - a/b*y;
20}
21int crt(int a[],int m[],int n)
22{
23    int M = 1;
24    int ans = 0 ;
25    for ( int i = 1 ; i <=  n; i++) M*=m[i];
 1    for ( int i = 1 ; i <= n ; i++)
 2    {
 3	int x,y;
 4	int Mi = M/m[i];
 5	exgcd(Mi,m[i],x,y);
 6	ans = ( ans + Mi * x * a[i])%M;
 7    }
 8    if (ans<0) ans+=M;
 9    return ans;
10}
11int main()
12{
13	#ifndef  ONLINE_JUDGE 
14	freopen("code/in.txt","r",stdin);
15  #endif
 1	int cas = 0 ;
 2	m[1] = 23;
 3	m[2] = 28;
 4	m[3] = 33;
 5	int T = 21252;
 6	while (~scanf("%d%d%d%d",&p,&e,&i,&d))
 7	{
 8	    if (p==-1&&e==-1&&i==-1&&d==-1) break;
 9	    a[1] = p;
10	    a[2] = e;
11	    a[3] = i;
12	    int ans = crt(a,m,3);
13	    if (ans-d<=0) ans += T; 
14	    printf("Case %d: the next triple peak occurs in %d days.\n",++cas,ans-d);
15	}
1  #ifndef ONLINE_JUDGE  
2  fclose(stdin);
3  #endif
4    return 0;
5}