Luo Gu p4777 [template] to expand Chinese remainder theorem

1 year ago has long been studying the same room had what I now scholarship, wtcl. The number of reset request \ (X \) .
Set the current process to the second \ (K \) th congruence expression, provided (M = the LCM ^ {K -. 1} _ {I -. 1} \) \ ,
before \ (k - 1 \) a general solution is to \ ( M * I + X \) .
So in fact, the first \ (k \) months, it
is actually seeking a \ (y \)
so that \ (x + y * M ≡
a_k (mod b_k) \) transforming what is the \ (y * M ≡ (a_k - x ) (mod b_k) \)
so \ (y \) we can use \ (exgcd \) seek out.
If solution,
then the first \ (K \) th congruence solution is then \ (x_k = x_ {k -
1} + y * M \) is actually seeking \ (K \) times extended Euclidean. .

#include <bits/stdc++.h>

typedef long long ll;

const int maxn = 100010;

template<class t> inline void read(t& res) {
    res = 0;  char ch = getchar();  bool neg = 0;  
    while(!isdigit(ch))
        neg |= ch == '-', ch = getchar();
    while(isdigit(ch))
        res = (res << 1) + (res << 3) + (ch & 15), ch = getchar();
    if(neg)
        res = -res;
}

ll n;
ll a[maxn], b[maxn];

inline ll mul(ll a,ll b,ll mod) {
    ll res = 0;
    while(b) {
        if(b & 1)
            res = (res + a) % mod;
        a = (a + a) % mod;
        b >>= 1;            
    }
    return res;
}
ll exgcd(ll a,ll b,ll& x,ll& y) {
    if(!b) {
        x = 1;  y = 0;
        return a;
    }
    ll res = exgcd(b,a % b,x,y);
    ll z = x;  x = y;  y = z - a / b * y;
    return res;   
}
inline ll excrt() {
    ll M = b[1], res = a[1], x, y;
    for(int i = 2;i <= n;i++) {
        ll A = M, B = b[i], C = (a[i] - res % B + B) % B;
        ll D = exgcd(A,B,x,y), E = B / D;
        x = mul(x,C / D,E);
        res += x * M;  
        M *= E;  
        res = (res % M + M) % M;  
    }
    return (res % M + M) % M;  
}

int main() {
    scanf("%lld",&n);
    for(int i = 1;i <= n;i++)
        scanf("%lld %lld",b + i,a + i);
    printf("%lld\n",excrt());
    return 0;  
}

Guess you like

Origin www.cnblogs.com/Sai0511/p/11233760.html