1. 程式人生 > >poj 2891 Strange Way to Express Integers 中國剩餘定理模板

poj 2891 Strange Way to Express Integers 中國剩餘定理模板

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 ≤ ik) 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 ≤ ik).

 

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.

 給出除數和餘數, 求最小公共解....

套用中國剩餘定理即可求解.....

程式碼如下:
 

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
typedef long long ll;
const int maxn=1005;
ll a[maxn],r[maxn];
int k;
ll Extend (ll A,ll B,ll& X,ll& Y)
{
    if(B==0)
    {
        X=1; Y=0;
        return A;
    }
    else
    {
        ll temp,ans;
        ans=Extend (B,A%B,X,Y);
        temp=X;
        X=Y;
        Y=temp-A/B*Y;
        return ans;
    }
}
ll solve ()
{
    ll x,y,d,c,t;
    for (int i=1;i<k;i++)
    {
        c=r[i]-r[i-1];
        d=Extend(a[i-1],a[i],x,y);
        if(c%d) return -1;
        x=c/d*x;
        t=a[i]/d;
        x=(x%t+t)%t;
        r[i]=a[i-1]*x+r[i-1];
        a[i]=a[i]/d*a[i-1];
    }
    return r[k-1];
}
int main()
{
    while (scanf("%d",&k)!=EOF)
    {
        for (int i=0;i<k;i++)
            scanf("%lld%lld",&a[i],&r[i]);
        ll ans=solve();
        printf("%lld\n",ans);
    }
    return 0;
}