POJ 2891 Strange Way to Express Integers(扩展欧几里得)

来源:互联网 发布:mac os x 13.1.02 编辑:程序博客网 时间:2024/06/07 03:14

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

详细题解请看博客

http://blog.csdn.net/qq_28954601/article/details/70226243

据说这是史上最全面的2891题解(´^ω^`)
然后附上自己代码

#include <iostream>#include<cstdio>using namespace std;#define ll __int64ll d;ll ex_gcd(ll a,ll b,ll &x,ll &y){    if(!b)    {        d=a,x=1,y=0;    }    else    {        ex_gcd(b,a%b,y,x);        y-=(a/b)*x;    }    return d;}int main(){    int T;    ll a1,r1,a2,r2;    bool flag;    while(~scanf("%d",&T))    {        flag=true;        scanf("%I64d %I64d",&a1,&r1);        T--;        ll x,y;        while(T--)        {            scanf("%I64d %I64d",&a2,&r2);            ll gcd=ex_gcd(a1,a2,x,y);            ll C=r1-r2;            if(C%gcd!=0)            {                flag=false;                for(int j=1;j<=T;j++)                    scanf("%I64d %I64d",&a2,&r2);                break;            }            else            {                x=(x*(C/gcd))%(a2/gcd);                r1-=x*a1;                a1=a1/gcd*a2;                r1%=a1;            }        }        if(!flag)            printf("-1\n");        else            printf("%I64d\n",(r1+a1)%a1);  //负数转换    }    return 0;}
1 0
原创粉丝点击