Strange Way to Express Integers POJ - 2891 数论

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
Hint
All integers in the input and the output are non-negative and can be represented by 64-bit integral types.

给出n组 ai,r1,求出最小的m 满足:
m%ai=ri;
如果不存在,输出-1;
思路:这题就是求解同余方程组: m=ri ( mod ai );
如果 ai 两两互质,那么就是中国剩余定理就可以解决了;

现在不一定互质;
那么我们就两个先考虑一下:即 m = r1+k1*a1; m = r2+k2*a2;
====> r1+k1*a1==r2+k2*a2 ======> a1k1-a2k2==r2-r1; 是不是很熟悉? 比较一下 ax+by==c ;那么我们只需用 exgcd 求解即可,求解出 k1之后,带入原来式子中,求出 m , 再将上一次的 ai,ri 更新,方便下次计算;

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<string>
#include<bitset>
#include<ctime>
#include<deque>
#include<stack>
#include<functional>
#include<sstream>
using namespace std;
typedef long long ll;
#define maxn 2000005
#define inf 0x3f3f3f3f

void exgcd(ll a,ll b,ll &d,ll &x,ll &y)
{
    if(b==0){
        x=1;y=0;d=a;
    }
    else {
        exgcd(b,a%b,d,y,x);
        y-=x*(a/b);
    }
}



int main()
{
    ios::sync_with_stdio(false);
    ll a1,a2,r1,r2,k1;
    int flag;
    ll n,m,k,t;
    ll z,x,y,a,b;
    ll d;
    while(cin>>n){
        n--;
        cin>>a1>>r1;
        flag=0;
        while(n--){
            cin>>a2>>r2;
            exgcd(a1,a2,d,z,y);
            if((r2-r1)%d)flag=1;
            k1=(r2-r1)/d*z;
            ll tmp=a2/d;
            k1=(k1%tmp+tmp)%tmp;
            x=r1+k1*a1;
            a1=(a1*a2)/d;r1=x;
        }
        if(flag)cout<<-1<<endl;
        else cout<<x<<endl;
    }
}





猜你喜欢

转载自blog.csdn.net/qq_40273481/article/details/81735763