Advertisement
Guest User

Untitled

a guest
Nov 21st, 2014
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. #include <cstdio>
  2. #include <iostream>
  3. #define MAX 1012
  4. #define LL long long
  5. #define BOUND 955049953
  6. using namespace std;
  7.  
  8. int T, N;
  9. long long P[MAX];
  10. long long R[MAX];
  11.  
  12. long long modinv(long long a, long long b){
  13. long long b0 = b, t, q;
  14. long long x0 = 0, x1 = 1;
  15. if (b == 1) return 1;
  16. while (a > 1) {
  17. q = a / b;
  18. t = b, b = a % b, a = t;
  19. t = x0, x0 = x1 - q * x0, x1 = t;
  20. }
  21. if (x1 < 0) x1 += b0;
  22. return x1;
  23. }
  24.  
  25. // a * k + eq_c = eq_r (mod M)
  26. long long solv(long long eq_a, long long eq_c, long long M, long long eq_r){
  27.  
  28.  
  29. //cout << eq_a << " * k + " << eq_c << " = " << eq_r << " (mod " << M << ")" << endl;
  30.  
  31. long long k = (eq_r - eq_c) * modinv(eq_a, M);
  32. k %= M;
  33. if (k < 0){ k += M; }
  34.  
  35. //cout << "k = " << k << endl;
  36.  
  37. return eq_a * k + eq_c;
  38. }
  39.  
  40. int main(){
  41.  
  42. ios::sync_with_stdio(false);
  43.  
  44. cin >> T;
  45. while(T--){
  46. cin >> N;
  47. for(int i = 0; i < N; ++i){ cin >> P[i] >> R[i]; }
  48.  
  49. long long res = R[0];
  50. long long C = P[0];
  51.  
  52. bool breakflag = 0;
  53.  
  54. for(int i = 1; i < N; ++i){
  55. res = solv(C, res, P[i], R[i]);
  56. if(res < 0){ res += P[i]; }
  57.  
  58. if (res >= BOUND) { breakflag = 1; break; }
  59. C *= P[i];
  60. }
  61.  
  62. if(breakflag){ cout << "-1" << endl; } else { cout << res << endl; }
  63.  
  64. }
  65. return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement