루오 구 p4777 [서식], 중국 잉여 정리를 확장

2 년 전 긴 같은 방을 공부하고하는 것은, wtcl을 내가 지금 장학금을했다. 리셋 요청의 수 \ (X \) .
두 번째로는 현재 프로세스를 설정 \ (K \) 제공 합동 식 번째 (M은 LCM ^ = {K한다. - 1} _ {I는 -. 1} \)는 \ ,
전에 \ (K - 1 \) 일반적인 솔루션이다 (\ M의 * 나는 X를 + \) .
그래서 사실, 첫 번째 \ (케이 \) 개월, 그것은
실제로 찾고 있습니다 \ (y를 \)를
그래서 \ (X + Y의 * M ≡
a_k (모드 b_k) \) 는 IS 어떤 변화 \ (Y *의 M의 ≡은 (a_k - X () 모드 b_k) \)
그래서 \ (y를 \) 우리가 사용할 수 있습니다 \ (exgcd \) 추구.
용액의 경우,
다음 제 \ (K \) 적합성 용액 후이다 번째 \ (x_k = X_ {K -
1} + y를 * m 개의 \) 실제로 찾고 \ (K \) 번 유클리드 연장. .

#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;  
}

추천

출처www.cnblogs.com/Sai0511/p/11233760.html