POJ——T 2891 Strange Way to Express Integers
http://poj.org/problem?id=2891
Time Limit: 1000MS | Memory Limit: 131072K | |
Total Submissions: 16849 | Accepted: 5630 |
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
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
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.
敲模板磨時間、、
1 #include <algorithm> 2 #include <cstdio> 3 4 using namespace std; 5 6 #define LL long long 7 const int N(1005); 8 LL n,a[N],m[N]; 9 10 LL exgcd(LL a,LL b,LL &x,LL &y) 11 { 12 if(!b) 13 { 14 x=1; y=0; 15 return a; 16 } 17 LL ret=exgcd(b,a%b,x,y),tmp=x; 18 x=y; y=tmp-a/b*y; 19 return ret; 20 } 21 LL CRT() 22 { 23 LL ret=m[1],tot=a[1]; 24 for(int i=2;i<=n;i++) 25 { 26 LL x,y,tt=a[i],c=m[i]-ret; 27 LL gcd=exgcd(tot,tt,x,y); 28 if(c%gcd) return -1; 29 x=x*c/gcd; 30 LL mod=tt/gcd; 31 x=(x%mod+mod)%mod; 32 ret+=x*tot; tot*=mod; 33 } 34 if(!ret) ret+=tot; 35 return ret; 36 } 37 38 int main() 39 { 40 for(;~scanf("%lld",&n);) 41 { 42 for(int i=1;i<=n;i++) 43 scanf("%lld%lld",a+i,m+i); 44 printf("%lld\n",CRT()); 45 } 46 return 0; 47 }
POJ——T 2891 Strange Way to Express Integers