Monkey Tradition---LightOj1319(中国剩余定理模板)

 

题目链接:http://lightoj.com/volume_showproblem.php?problem=1319

 

题意:有 n 个猴子,n 棵树,树的高度为 L ,每个猴子刚开始的时候都在树的底部,后来往上跳,每次跳的距离是pi,最后不能跳到树上面所以最后会有个到顶端的距离ri,求L的最小值;

典型的模板题;

中国剩余定理详解:http://www.cnblogs.com/zhengguiping--9876/p/5319813.html

 

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>

#define MAXN 22
typedef long long LL;

void ex_gcd(LL a, LL b, LL &x, LL &y)
{
    if(b==0)
    {
        x = 1;
        y = 0;
        return ;
    }
    ex_gcd(b, a%b, x, y);
    LL temp = x;
    x = y;
    y = temp - a/b * y;
    if(a*b<0)
    {
        x = -x;
        y = -y;
    }
}
int main()
{
    LL  A[MAXN], R[MAXN], N0, N[MAXN];

    int n, T, t = 1;

    scanf("%d", &T);

    while(T--)
    {
        scanf("%d", &n);

        memset(A, 0, sizeof(A));
        memset(R, 0, sizeof(R));
        memset(N, 0, sizeof(N));

        N0 = 1;

        for(int i=1; i<=n; i++)
        {
            scanf("%lld %lld", &A[i], &R[i]);
            N0 *= A[i];
        }

        LL x = 0;

        for(int i=1; i<=n; i++)
        {
            LL K, K0;

            ex_gcd(N0/A[i], -A[i], K, K0);

            N[i] = A[i] * K0 + 1; ///或者 N[i] = N0/A[i] * K;

            x = (x + N[i] * R[i] + N0) % N0;
        }
        printf("Case %d: %lld\n", t++, (x+N0)%N0);
    }
    return 0;
}

 

posted @ 2016-03-25 16:36  西瓜不懂柠檬的酸  Views(413)  Comments(0)    收藏  举报
levels of contents