码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 3579

时间:2015-08-05 14:46:43      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

标准同余方程组,只是在求出值后如果为0,应该输出Mi的Lcm;

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long LL;
LL Ai[50],Ri[50];
LL gcd(LL a, LL b)
{
    return b ? gcd(b,a%b) : a;
}
void Exgcd(LL a,LL b,LL& d,LL& x,LL& y)
{
    if(b == 0) { d = a; x = 1; y = 0;}
    else { Exgcd(b,a%b,d,y,x); y -= x*(a/b); }
}
LL ModN(LL* Ai,LL* Ri,LL n)
{
    LL a1 = Ai[1], r1 = Ri[1];
    LL X,Y,D;
    bool Jug = true;
    for(LL i = 2; i <= n; ++i)
    {
        //if(Jug == false) break;
        LL a = a1, b = Ai[i], c = Ri[i] - r1;
        Exgcd(a,b,D,X,Y);
        if(c % D)
        {
            Jug = false;
            return -1;
        }
        LL t = b / D;
        X = (X * (c / D) % t + t) % t;
        r1 += a1 * X;
        a1 *= Ai[i] / D;
    }
    return r1;
}
int main()
{
    int t;
    LL N;
    int Case = 1;
    cin >> t;
    while(t --)
    {
        cin >> N;
        for(int i = 1; i <= N; ++i)
            cin >> Ai[i];
        for(int i = 1; i <= N; ++i)
            cin >> Ri[i];
        LL ans = ModN(Ai,Ri,N);
        printf("Case %d: ",Case++);
        if(ans == -1) cout << "-1\n";
        else if(ans != 0) cout << ans << endl;
        else {
            LL Lcm = 1;
            for(int i = 1; i <= N; ++i)
                Lcm = Lcm / gcd(Lcm,Ai[i]) * Ai[i];
            cout << Lcm << endl;
        }
    }
}

HDU 3579

标签:

原文地址:http://www.cnblogs.com/aoxuets/p/4704579.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!