poj Strange Way to Express Integers 中国剩余定理
Time Limit: 1000MS | Memory Limit: 131072K | |
Total Submissions: 8193 | Accepted: 2448 |
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 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.
要考虑0的情况,注意输入,,看清题意
1 #include<iostream> 2 #include<cstdio> 3 #include<cstdlib> 4 #include<cstring> 5 using namespace std; 6 7 8 __int64 Ex_gcd(__int64 a,__int64 b,__int64 &x,__int64 &y) 9 { 10 if(b==0) 11 { 12 x=1; 13 y=0; 14 return a; 15 } 16 __int64 g=Ex_gcd(b,a%b,x,y); 17 __int64 hxl=x-(a/b)*y; 18 x=y; 19 y=hxl; 20 return g; 21 } 22 23 __int64 gcd(__int64 a,__int64 b) 24 { 25 if(b==0) 26 return a; 27 return gcd(b,a%b); 28 } 29 30 int main() 31 { 32 __int64 k,m1,m2,r1,r2,x,y,t,i,d,c; 33 __int64 sum1=1,sum2; 34 bool flag; 35 while(scanf("%I64d",&k)>0) 36 { 37 scanf("%I64d%I64d",&m1,&r1); 38 sum1=m1;sum2=m1; 39 flag=false; 40 for(i=2;i<=k;i++) 41 { 42 scanf("%I64d%I64d",&m2,&r2); 43 44 if(flag==true) continue; 45 sum1=sum1*m2; 46 sum2=gcd(sum2,m2); 47 d=Ex_gcd(m1,m2,x,y); 48 c=r2-r1; 49 if(c%d) 50 { 51 flag=true; 52 continue; 53 } 54 x=c/d*x; 55 t=m2/d; 56 x=(x%t +t)%t; 57 r1=m1*x+r1; 58 m1=m1*m2/d; 59 } 60 if(flag==true) 61 { 62 printf("-1\n"); 63 continue; 64 } 65 if(r1==0) 66 { 67 r1=sum1/sum2; 68 } 69 printf("%I64d\n",r1); 70 } 71 return 0; 72 }