1. 程式人生 > >poj 1006 生理週期 【中國剩餘定理】

poj 1006 生理週期 【中國剩餘定理】

生理週期
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 117999 Accepted: 37040
Description

人生來就有三個生理週期,分別為體力、感情和智力週期,它們的週期長度為23天、28天和33天。每一個週期中有一天是高峰。在高峰這天,人會在相應的方面表現出色。例如,智力週期的高峰,人會思維敏捷,精力容易高度集中。因為三個週期的周長不同,所以通常三個週期的高峰不會落在同一天。對於每個人,我們想知道何時三個高峰落在同一天。對於每個週期,我們會給出從當前年份的第一天開始,到出現高峰的天數(不一定是第一次高峰出現的時間)。你的任務是給定一個從當年第一天開始數的天數,輸出從給定時間開始(不包括給定時間)下一次三個高峰落在同一天的時間(距給定時間的天數)。例如:給定時間為10,下次出現三個高峰同天的時間是12,則輸出2(注意這裡不是3)。
Input

輸入四個整數:p, e, i和d。 p, e, i分別表示體力、情感和智力高峰出現的時間(時間從當年的第一天開始計算)。d 是給定的時間,可能小於p, e, 或 i。 所有給定時間是非負的並且小於365, 所求的時間小於21252。

當p = e = i = d = -1時,輸入資料結束。
Output

從給定時間起,下一次三個高峰同天的時間(距離給定時間的天數)。

採用以下格式:
Case 1: the next triple peak occurs in 1234 days.

注意:即使結果是1天,也使用複數形式“days”。
Sample Input

0 0 0 0
0 0 0 100
5 20 34 325
4 5 6 7
283 102 23 320
203 301 203 40
-1 -1 -1 -1
Sample Output

Case 1: the next triple peak occurs in 21252 days.
Case 2: the next triple peak occurs in 21152 days.
Case 3: the next triple peak occurs in 19575 days.
Case 4: the next triple peak occurs in 16994 days.
Case 5: the next triple peak occurs in 8910 days.
Case 6: the next triple peak occurs in 10789 days.
Source

East Central North America 1999

裸的中國剩餘定理

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <ctype.h>
#include <time.h>
#include <queue>

using namespace std;

int p, e, i, d;

long long ext_gcd(long long a, long long b, long long &x, long long &y)
{
    if (a == 0 && b == 0) return -1;
    if (b == 0)
    {
        x = 1;
        y = 0;
        return a;
    }
    long long d = ext_gcd(b, a%b, y, x);
    y -= a / b*x;
    return d;
}

//求逆元素
// ax=1(mod n)
long long mod_reverse(long long a, long long n)
{
    long long x, y;
    long long d = ext_gcd(a, n, x, y);
    if (d == 1)
        return (x%n + n) % n;
    else
        return -1;
}

int cases = 1;

int main()
{
    while (cin >> p >> e >> i >> d)
    {
        if (p == -1 && e == -1 && i == -1 && d == -1)
            return 0;
        int d1 = p * 33 * 28 * mod_reverse(33 * 28, 23);
        int d2 = e * 23 * 33 * mod_reverse(23 * 33, 28);
        int d3 = i * 23 * 28 * mod_reverse(23 * 28, 33);
        int ans = ((d1 + d2 + d3 - d) % (23 * 28 * 33) + (23 * 28 * 33)) % (23 * 28 * 33);
        if (ans == 0) ans = (23 * 28 * 33);
        printf("Case %d: the next triple peak occurs in %d days.\n",cases++,ans);
    }
    return 0;
}