POJ——T 2891 Strange Way to Express Integers

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 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 integer k.
  • Lines 2 ~ k + 1: Each contains a pair of integers airi (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.

 

敲模板磨时间、、

 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的主要内容,如果未能解决你的问题,请参考以下文章

poj——2891 Strange Way to Express Integers

POJ 2891 Strange Way to Express Integers

poj 2891 Strange Way to Express Integers 2012-09-05

POJ2891Strange Way to Express Integers(拓展CRT)

poj 2891 Strange Way to Express Integers(中国剩余定理)

POJ-2891-Strange Way to Express Integers(线性同余方程组)