POJ_2891
两个同余方程是可以合并成一个同余方程的,就这样一直合并直到没法合并为止,注意运算过程中要合理地使用模操作来避免中间结果超出long long。
#include<stdio.h> #include<string.h> #include<algorithm> typedef long long LL; int K; void exgcd(LL a, LL b, LL &d, LL &x, LL &y) { if(b == 0) d = a, x = 1, y = 0; else exgcd(b, a % b, d, y, x), y -= x * (a / b); } int main() { while(scanf("%d", &K) == 1) { bool ok = true; LL a1, r1, a2, r2; scanf("%lld%lld", &a1, &r1); for(int i = 1; i < K; i ++) { scanf("%lld%lld", &a2, &r2); if(!ok) continue; LL k1, k2, d; exgcd(a1, a2, d, k1, k2); if((r2 - r1) % d != 0) ok = false; else { LL t = a2 / d; k1 = (r2 - r1) / d % t * (k1 % t) % t; r1 = a1 * k1 + r1, a1 = a2 / d * a1, r1 %= a1; } } if(!ok) printf("-1\n"); else printf("%lld\n", (r1 % a1 + a1) % a1); } return 0; }