POJ2891Strange Way to Express Integers 中國剩餘定理普通情況

http://poj.org/problem?id=2891

Strange Way to Express Integers

Time Limit: 1000MS   Memory Limit: 131072K
Total Submissions: 21436   Accepted: 7181

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 (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.

Source

 

#include<iostream>
# define ll long long
using namespace std;
const ll maxn=1005;
ll m[maxn],a[maxn],s[maxn];
ll gcd(ll a,ll b)
{
    return b?gcd(b,a%b):a;
}
void extend(ll a, ll b, ll &x, ll &y)
{
    if(b == 0)
    {
        x = 1;
        y = 0;
        return;
    }
    extend(b, a % b, x, y);
    ll tmp = x;
    x = y;
    y = tmp - (a / b) * y;
}


ll Inv(ll a,ll b)
{

    ll d = gcd(a, b);

    if(d != 1)	return -1;

    ll x,y;

    extend(a, b, x, y);

    return (x % b+ b) % b;

}

bool ok(ll a1,ll m1,ll a2,ll m2,ll &a3,ll &m3)
{
    ll d=gcd(m1,m2);
    ll c=a2-a1;
    if(c%d)	return false;
    c=(c%m2+m2)%m2;
    m1/=d;
    m2/=d;
    c/=d;
    c*=Inv(m1,m2);
    c%=m2;
    c*=m1*d;
    c+=a1;
    m3=m1*m2*d;
    a3=(c%m3+m3)%m3;
    return true;
}
ll answer(ll a[],ll m[],int n)
{
    ll a1=a[1];
    ll m1=m[1];
    for(int i=2; i<=n; i++)
    {
        ll a2=a[i];
        ll m2=m[i];
        ll m3,a3;
        if(!ok(a1,m1,a2,m2,a3,m3))
            return -1;
        a1=a3;
        m1=m3;
    }
    return (a1%m1+m1)%m1;
}
int main()
{
    int n;
    while(cin>>n)
    {
        for(ll i=1; i<=n; i++)
        {
            cin>>m[i]>>a[i];
        }
        ll k=answer(a,m,n);
        cout<<k<<endl;
    }
    return 0;
}



 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章