poj 2891 (一般模线性方程组)

一般模线性方程组裸题,记录下模板。模板来源:http://www.cnblogs.com/Missa/archive/2013/06/01/3112536.html

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

你可能感兴趣的:(poj 2891 (一般模线性方程组))