Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdio>
- #include <iostream>
- #define MAX 1012
- #define LL long long
- #define BOUND 955049953
- using namespace std;
- int T, N;
- long long P[MAX];
- long long R[MAX];
- long long modinv(long long a, long long b){
- long long b0 = b, t, q;
- long long x0 = 0, x1 = 1;
- if (b == 1) return 1;
- while (a > 1) {
- q = a / b;
- t = b, b = a % b, a = t;
- t = x0, x0 = x1 - q * x0, x1 = t;
- }
- if (x1 < 0) x1 += b0;
- return x1;
- }
- // a * k + eq_c = eq_r (mod M)
- long long solv(long long eq_a, long long eq_c, long long M, long long eq_r){
- //cout << eq_a << " * k + " << eq_c << " = " << eq_r << " (mod " << M << ")" << endl;
- long long k = (eq_r - eq_c) * modinv(eq_a, M);
- k %= M;
- if (k < 0){ k += M; }
- //cout << "k = " << k << endl;
- return eq_a * k + eq_c;
- }
- int main(){
- ios::sync_with_stdio(false);
- cin >> T;
- while(T--){
- cin >> N;
- for(int i = 0; i < N; ++i){ cin >> P[i] >> R[i]; }
- long long res = R[0];
- long long C = P[0];
- bool breakflag = 0;
- for(int i = 1; i < N; ++i){
- res = solv(C, res, P[i], R[i]);
- if(res < 0){ res += P[i]; }
- if (res >= BOUND) { breakflag = 1; break; }
- C *= P[i];
- }
- if(breakflag){ cout << "-1" << endl; } else { cout << res << endl; }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement