【数论】X问题(扩展中国剩余定理)

http://icpc.upc.edu.cn/problem.php?cid=1437&pid=19

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=15;
ll t,a[N],b[N],ans,lcm,f,n,m;
ll gcd(ll a,ll b) {
    if (!b) {
        return a;
    }
    return gcd(b, a % b);
}
ll exgcd(ll a,ll b,ll &x,ll&y) {
    if (!b) {
        x = 1;
        y = 0;
        return a;
    }
    ll d = exgcd(b, a % b, y, x);
    y -= a / b * x;
    return d;
}
ll China(ll n) {
    ll a1 = a[1], b1 = b[1], a2, b2, x1, y1, x0, g, c;
    lcm = a[1];
    for (int i = 2; i <= n; i++) {
        a2 = a[i];
        b2 = b[i];
        c = b2 - b1;
        g = exgcd(a1, a2, x1, y1);
        lcm = lcm * a[i] / gcd(lcm, a[i]);
        if (c % g) {
            f = 0;
            return 0;
        }
        x0 = x1 * c / g;
        ll t = a2 / g;
        x0 = (x0 % t + t) % t;
        b1 += a1 * x0;
        a1 = a2 / g * a1;
    }
    return b1;
}
int main() {
    scanf("%lld", &t);
    while (t--) {
        scanf("%lld%lld", &n, &m);
        for (ll i = 1; i <= m; i++) {
            scanf("%lld", &a[i]);
        }
        for (ll i = 1; i <= m; i++) {
            scanf("%lld", &b[i]);
        }
        f = 1;
        ans = China(m);
        if (!f || ans > n) {
            printf("0\n");
        } else {
            if (ans <= 0) ans += lcm;
            ans = (n - ans) / lcm +1;
            printf("%lld\n", ans);
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值