扩展欧几里得,注意防溢出。
http://poj.org/problem?id=2891
1 #include <cstdio> 2 using namespace std; 3 typedef __int64 LL; 4 const int maxn = 1e5 + 10; 5 6 LL a[maxn], r[maxn]; 7 int n; 8 LL egcd(LL a, LL b, LL& x, LL& y){ 9 if(!b){ 10 x = 1, y = 0; 11 return a; 12 } 13 LL d = egcd(b, a % b, x, y); 14 LL t = x; 15 x = y; 16 y = t - a / b * y; 17 return d; 18 } 19 20 void solve(){ 21 LL R = r[0], A = a[0], x, y; 22 for(int i = 1; i < n; i++){ 23 LL a1 = A, b1 = a[i], m = r[i] - R; 24 LL d = egcd(a1, b1, x, y); 25 if(m % d != 0){ 26 printf("-1 "); 27 return; 28 } 29 LL t = A; 30 LL B = a[i] / d; 31 R += (m / d * x) % B * A; 32 A *= B; 33 if(R < 0) R += ((-R) / A + 2)* A; 34 R %= A; 35 } 36 printf("%I64d ", R); 37 } 38 39 int main(){ 40 freopen("in.txt", "r", stdin); 41 while(~scanf("%d", &n)){ 42 for(int i = 0; i < n; i++) scanf("%I64d%I64d", &a[i], &r[i]); 43 solve(); 44 } 45 return 0; 46 }