Strange Way to Express Integers Time Limit: 1000MS Memory Limit: 131072KTotal Submissions: 4191 Accepted: 1100
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 a1, a2, …, ak. For some non-negative m, divide it by every ai (1 ≤ i ≤ k) to find the remainder ri. If a1, a2, …, ak are properly chosen, m can be determined, then the pairs (ai, ri) 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 integer k. Lines 2 ~ k + 1: Each contains a pair of integers ai, ri (1 ≤ i ≤ k).
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 9Sample Output
31Hint
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
/* 对于w[1],w[2].....w[n]不互素的情形,就只能两个两个来求了 x=a[1] (mod m[1]) x=a[2] (mod m[2]) 解完后,a=x,m=m1和m2的最小公倍数 将题目意思转化为公式:a1*x-a2*y=r2-r1,用欧几里得扩展算法求解 a1+m1*y=a2+m2*z ==> a1-a2=m2*z-m1*y 则(a1-a2)%gcd(m1,m2)=0 则:x=a2+m2*z (1) (应该a>m,必需条件) x=r1 (mod a1) x=r2 (mod a2) ---> //a1*x+a2*y=gcd(a1,a2)=d ---> //r1+a1*x=r2+a2*y ---> a1*x+a2*y=r2-r1 则(r2-r1)%d!=0 不能得出 否则 { t=a2/d; x=((x*(r2-r1)/d)%t+t)%t//x的最小整数解 r1=x*a1+r1 //由(1)式 a1=a1*a2/d; r1=(r1%a1+a1)%a1; } */ #include<cstdio> #include<cstdlib> long long int ex_Gcd(long long int p,long long int q,long long int &x,long long &y) { long long int temp,r; if(q==0) { x=1; y=0; return p; } r=ex_Gcd(q,p%q,x,y); temp=x; x=y; y=temp-p/q*y; return r; } int main() { long long int n,a1,a2,r1,r2,x,y,i,d,t; bool flag; while(scanf("%lld",&n)!=EOF) { scanf("%lld %lld",&a1,&r1); if(n==1) { if(a1<=r1) //余数不可能大于除数 printf("-1/n"); else printf("%lld/n",r1); continue; } flag=true; for(i=1; i<n; i++) { scanf("%lld %lld",&a2,&r2); if(!flag) continue; if(a2<=r2) flag=false; d=ex_Gcd(a1,a2,x,y);//a1*x+a2*y=gcd(a1,a2) if((r2-r1)%d!=0) flag=false; else { t=a2/d; x=((r2-r1)/d*x%t+t)%t; r1=x*a1+r1; a1=a1*a2/d; //a1为a1和a2的最小公倍数 r1=(r1%a1+a1)%a1; } } if(flag) printf("%lld/n",r1); else printf("-1/n"); } return 0; }