Problem D:Strange Way to Express Integers(POJ-2891)

Problem 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, ” 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 ≤ 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

—————————————————————————————————————————

题意:存在一个数 x,满足 x%ai = ri,现给出 n 对 ai 和 ri,求 x 的最小非负整数,如果不存在输出-1

思路:不互素的中国剩余定理,具体思路:点击这里

Source Program

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<cstdlib>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<ctime>
#include<vector>
#define INF 0x3f3f3f3f
#define PI acos(-1.0)
#define N 1005
#define MOD 1e9+7
#define E 1e-6
typedef long long ll;
using namespace std;
ll Extended_GCD(ll a,ll b,ll &x,ll &y)
{
    if(b==0)
    {
        x=1;
        y=0;
        return a;
    }

    int temp;
    int gcd=Extended_GCD(b,a%b,x,y);
    temp=x;
    x=y;
    y=temp-a/b*y;
    return gcd;
}
int main()
{
    ll n;
    while(scanf("%lld",&n)!=EOF)
    {
        ll a1,r1;
        cin>>a1>>r1;

        if(n==1)
        {
            if(a1<=r1)//余数不可大于除数
                cout<<-1<<endl;
            else
                cout<<r1<<endl;
            continue;
        }

        bool flag=true;
        for(ll i=1;i<n;i++)
        {
            ll a2,r2;
            cin>>a2>>r2;

            if(!flag)
                continue;

            if(a2<=r2)//余数不可大于除数
                flag=false;

            ll x,y;
            ll gcd=Extended_GCD(a1,a2,x,y);//a1*x+a2*y=gcd(a1,a2)

            if((r2-r1)%gcd!=0)
                flag=false;
            else
            {
                ll temp=a2/gcd;
                x=((r2-r1)/gcd*x%temp+temp)%temp;
                r1=x*a1+r1;

                a1=a1*a2/gcd;//此时a1为a1与a2的最小公倍数
                r1=(r1%a1+a1)%a1;
            }
        }

        if(flag)
            cout<<r1<<endl;
        else
            cout<<-1<<endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/u011815404/article/details/81536471