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

HDU 1573

时间:2015-08-05 12:41:18      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
/*
同余方程组为 X = ri (mod ai)
在范围内求X的个数
先求出特解 X0;
求出 ai数组的LCM;
则有 Xi = X0+LCM 均能满足方程组,判断是否在范围内!!
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long LL;
LL Ai[20],Ri[20];
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 Solve(LL* ai,LL* ri,LL n)
{
    LL r1 = ri[1], a1 = ai[1];
    LL x, y;
    bool Jug = true;
    for(LL i = 2; i <= n; ++i)
    {
        LL d;
        LL a = a1, b = ai[i], c = ri[i] - r1;
        Exgcd(a,b,d,x,y);
        if(c % d) Jug = false;
        LL t = b / d;
        x = (x * (c / d)% t+ t)%t;
        r1 = a1 * x + r1;
        a1 = a1 * (ai[i]/d);
    }
    if(Jug) return r1;
    else return -1;
}
LL gcd(LL a,LL b) {return b ? gcd(b,a%b) : a;}
int main()
{
    LL N,M,T;
    cin >> T;
    while(T--)
    {
        cin >> N >> M;
        LL Lcm = 1;
        for(LL i = 1; i <= M; ++i)
        {
            cin >> Ai[i];
            Lcm = Lcm / gcd(Lcm,Ai[i]) * Ai[i];
        }
        for(LL i = 1; i <= M; ++i)
        {
            cin >> Ri[i];
        }
        LL tmp = Solve(Ai,Ri,M);
        //cout << Lcm << endl;
        if(tmp == -1) cout << "0\n";
        else
        {
            LL ans = 0;
            if(tmp <= N) ans = 1 + (N - tmp) / Lcm;
            if(tmp == 0 && ans > 0) ans --;
            cout << ans << endl;
        }
    }
}

HDU 1573

标签:

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

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