【题解】poj2891 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 ≤ 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.


大佬题解非常好,去看他的

#include<cstdio>
const int N=1e5+10;
typedef long long ll;
ll k,a[N],r[N];
bool flag;
ll exgcd(ll a,ll b,ll &x,ll &y)
{
    if(!b){x=1,y=0;return a;}
    ll d=exgcd(b,a%b,y,x);
    y-=a/b*x;
    return d;
}
int main()
{
    //freopen("in.txt","r",stdin);
    while(~scanf("%lld",&k))
    {
        flag=true;
        for(int i=1;i<=k;i++)scanf("%lld%lld",&a[i],&r[i]);
        ll m=a[1],t=r[1],x,y,d;
        for(int i=2;i<=k;i++)
        {
            d=exgcd(m,a[i],x,y);
            if((t-r[i])%d!=0){puts("-1");flag=false;break;}
            x=(t-r[i])/d*x%a[i];
            t-=x*m;
            m=m/d*a[i];
            t%=m;
        }
        if(flag)printf("%lld\n",(t%m+m)%m);
    }
    return 0;
}

总结

我对扩欧不熟

猜你喜欢

转载自blog.csdn.net/qq_41958841/article/details/82503344