首页 > 代码库 > poj——2891 Strange Way to Express Integers

poj——2891 Strange Way to Express Integers

                      Strange Way to Express Integers
Time Limit: 1000MS Memory Limit: 131072K
Total Submissions: 16839 Accepted: 5625

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

28 711 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
 
今天最后一个中国剩余定理、、、、、、(还是水体。。。。。)

题目大意: 有一个数mod ri 等于ai  ,求这个数,若求不出来输出“-1”。

代码:
#include<cstdio>#include<cstring>#include<cstdlib>#include<iostream>#include<algorithm>#define N 1000#define ll long longusing namespace std;ll n,a[N],m[N];ll read(){    ll x=0,f=1; char ch=getchar();    while(ch<0||ch>9){if(ch==-)f=-1; ch=getchar();}    while(ch>=0&&ch<=9){x=x*10+ch-0; ch=getchar();}    return x*f;}ll exgcd(ll a,ll b,ll &x,ll &y){    if(b==0)    {        x=1,y=0;        return a;    }    ll r=exgcd(b,a%b,x,y),tmp;    tmp=x,x=y,y=tmp-a/b*y;    return r;}ll crt(){    ll a1=a[1],m1=m[1],a2,m2,c,d;    for(ll i=2;i<=n;i++)    {        m2=m[i],a2=a[i];        c=a2-a1;ll x=0,y=0;        d=exgcd(m1,m2,x,y);        if(c%d) return -1;        x=x*c/d;        int mod=m2/d;        x=(mod+x%mod)%mod;        a1+=x*m1;m1*=mod;    }    if(a1==0) a1+=m1;    return a1;}int main(){    while(~scanf("%lld",&n))    {        for(ll i=1;i<=n;i++)         m[i]=read(),a[i]=read();        printf("%lld\n",crt());    }    return 0;}

 

poj——2891 Strange Way to Express Integers