Strange Way to Express Integers

Time Limit: 1000MS

 

Memory Limit: 131072K

Total Submissions: 14626

 

Accepted: 4787

Description

 

Elina is reading a book written by Rujia Liu, which introduces a strange way to express non-negative integers. The way is described as following:

 

Choose k different positive integers a1a2, …, ak. For some non-negative m, divide it by every ai (1 ≤ i ≤ k) to find the remainder ri. If a1a2, …, ak are properly chosen, m can be determined, then the pairs (airi) can be used to express m.

“It is easy to calculate the pairs from m, ” said Elina. “But how can I find m from the pairs?”

Since Elina is new to programming, this problem is too difficult for her. Can you help her?

Input

The input contains multiple test cases. Each test cases consists of some lines.

  • Line 1: Contains the integerk.
  • Lines 2 ~k+ 1: Each contains a pair of integersai,ri(1 ≤ik).

 

Output

Output the non-negative integer m on a separate line for each test case. If there are multiple possible values, output the smallest one. If there are no possible values, output -1.

 

Sample Input

2
8 7
11 9

Sample Output

31

Hint

All integers in the input and the output are non-negative and can be represented by 64-bit integral types.

Source

​POJ Monthly--2006.07.30​​, Static

1 #include "bits/stdc++.h"
2 using namespace std;
3 typedef long long LL;
4 const int MAX=10005;
5 LL cas;
6 LL n;
7 LL aa[MAX],r[MAX];
8 LL exgcd(LL a,LL b,LL &x,LL &y){
9 if (b==0){x=1,y=0;return a;}
10 LL d=exgcd(b,a%b,x,y),t=x;x=y,y=t-(a/b)*y;
11 return d;
12 }
13 LL modeqset(){
14 LL i,j;
15 LL a,b,c,d,x,y,t;
16 for (i=2;i<=n;i++){
17 a=aa[i-1],b=aa[i];
18 c=r[i]-r[i-1];
19 d=exgcd(a,b,x,y);
20 if (c%d) return -1;
21 t=b/d;
22 x=(x*(c/d)%t+t)%t;
23 r[i]=r[i-1]+aa[i-1]*x;
24 aa[i]=aa[i]/d*aa[i-1];
25 }
26 return r[n];
27 }
28 int main(){
29 freopen ("way.in","r",stdin);
30 freopen ("way.out","w",stdout);
31 LL i,j;
32 while (~scanf("%lld",&n)){
33 for (i=1;i<=n;i++)
34 scanf("%lld%lld",aa+i,r+i);
35 LL ans=modeqset();
36 printf("%lld\n",ans);
37 }
38 return 0;
39