1. 程式人生 > >poj 2891 (一般模線性方程組)

poj 2891 (一般模線性方程組)

#include <stdio.h>
typedef long long LL;
const int maxn = 1e5+10;
const int inf = 0x3f3f3f3f;
int n;
void ex_gcd(LL a, LL b, LL &d, LL &x, LL &y){
    if(!b){
        d = a; x = 1; y = 0;
    }else{
        ex_gcd(b, a % b, d, y, x); y -= x * (a / b);
    }
}
//一般模線性方程
LL ex_crt(LL *m, LL *r, int
n){ LL M = m[1], R = r[1], x, y, d; for (int i = 2; i <= n; ++i) { ex_gcd(M, m[i], d, x, y); if ((r[i] - R) % d) return -1; x = (r[i] - R) / d * x % (m[i] / d); R += x * M; M = M / d * m[i]; R %= M; } return R > 0 ? R : R + M; } LL m[maxn], r[maxn]; int
main() { int n; while(scanf("%d", &n) != EOF) { for(int i = 1; i <= n; i++){ scanf("%lld%lld", &m[i], &r[i]); } LL ans = ex_crt(m, r, n); printf("%lld\n", ans); } return 0; }