52: Luogu 4777 excrt

模板题

#include <bits/stdc++.h>

using namespace std;

const int N = 1e5 + 10;

#define LL long long

int n;
LL a[N], m[N];

LL Gcd(LL a, LL b) {
    return b == 0 ? a : Gcd(b, a % b);
}

void Exgcd(LL a, LL b, LL &x, LL &y) {
    if(b == 0) {
        x = 1, y = 0;
        return ;
    }
    Exgcd(b, a % b, x, y);
    LL tmp = x;
    x = y;
    y = tmp - a / b * y;
}

LL Mul(LL a, LL b, LL mod) {
    LL ret = 0;
    while(b) {
        if(b & 1) ret = (ret + a) % mod;
        b >>= 1;
        a = (a + a) % mod;
    }
    return ret;
}

void Merge(LL &a1, LL &m1, LL a2, LL m2) {
    LL k1, k2;
    Exgcd(m1, m2, k1, k2);
    LL gcd = Gcd(m1, m2);
    LL c = ((a2 - a1) % m2 + m2) % m2;
    Exgcd(m1, m2, k1, k2);
    k1 = Mul(k1, c / gcd, m2);
    a1 += (m1 * k1);
    m1 *= m2 / gcd;
    a1 = (a1 % m1 + m1) % m1;
}

int main() {
    cin >> n;
    LL A, M;
    for(int i = 1; i <= n; i ++) cin >> m[i] >> a[i];
    A = a[1], M = m[1];
    for(int i = 2; i <= n; i ++) {
        Merge(A, M, a[i], m[i]);
    }
    cout << A;
    return 0;
}

 

posted @ 2018-11-06 19:29  xayata  阅读(132)  评论(0编辑  收藏  举报