hdu1573 X问题 一元模线性方程组

/*
    题目描述:给出含m(1<= m <= 10)个形如x=bi (mod ai)的模线性方程组,问该方程组小于等于(1 <= n <= 1e9)
              的解有多少个?
    
    方法:正常解一元模线性方程组,自上向下合并,直至仅剩一个方程x = r (mod lcm(a1 ,a2 ,...,am)),若r > n 无解;
          否则令r+lcm*x <= n,解出x,若r不等于0则x++,x即为答案
*/
#pragma warning(disable:4786)
#pragma comment(linker, "/STACK:102400000,102400000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<vector>
#include<cmath>
#include<string>
#include<sstream>
#define LL long long
#define FOR(i,f_start,f_end) for(int i=f_start;i<=f_end;++i)
#define mem(a,x) memset(a,x,sizeof(a))
#define lson l,m,x<<1
#define rson m+1,r,x<<1|1
using namespace std;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const double PI = acos(-1.0);
const double eps=1e-8;
LL a[15], b[15];
LL n , m;
LL ex_gcd(LL a , LL b , LL &x ,LL &y)
{
    if(b==0){
        x = 1 ;     y = 0;
        return a;
    }
    LL d = ex_gcd(b , a%b , y , x);
    y = y - a / b * x;
    return d;
}
LL solve()
{
    LL a1 , r1 , a2 , r2 , x0 , y0;
    bool ok = 1;
    a1 = a[1];      r1 = b[1];
    for(int i = 2 ; i <= m ; i++){
        a2 = a[i] ;     r2 = b[i];
        LL d = ex_gcd(a1 , a2 , x0 , y0);
        LL c = r2 - r1;
        if(c % d){
            ok = 0;
        }
        LL m= a2 / d;
        x0 = (x0 * c / d % m + m)%m;
        r1 = a1 * x0 + r1;
        a1 = a1 * (a2 / d);
    }
    if(!ok)     return -1;
    else{
        if(n < r1)      return -1;
        LL ret = (n - r1 ) / a1 ;
        if(r1 !=0)      ++ret ;
        return ret;
    }
}
int main()
{
    int T  ;
    scanf("%d",&T);
    while(T--){
        scanf("%lld%lld",&n,&m);
        FOR(i , 1 , m)  scanf("%lld",&a[i]);
        FOR(i , 1 , m)  scanf("%lld",&b[i]);
        LL ans = solve();
        if(ans != -1)
            printf("%lld\n",ans);
        else
            printf("0\n");
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值