POJ-2891 Strange Way to Express Integers【扩展中国剩余定理】

Time limit1000 ms
Memory limit131072 kB

Descript

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.

Hint

All integers in the input and the output are non-negative and can be represented by 64-bit integral types.


大意就是有一个非负整数m
告诉你一组 m mod a i = r i 中的 a i r i
求问m最小值


题目分析

扩展中国剩余定理的模板题
具体解释看这里

中国剩余定理详解


#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long lt;

int n;
lt a[100010],r[100010];

lt read()
{
    lt f=1,x=0;
    char ss=getchar();
    while(ss<'0'||ss>'9'){if(ss=='-')f=-1;ss=getchar();}
    while(ss>='0'&&ss<='9'){x=x*10+ss-'0';ss=getchar();}
    return f*x;
}

lt exgcd(lt a,lt b,lt &x,lt &y)
{
    if(b==0){x=1;y=0;return a;}
    lt gcd=exgcd(b,a%b,x,y);
    lt tp=x;
    x=y; y=tp-a/b*y;
    return gcd;
}

lt china()
{
    lt M=a[1],ans=r[1],x,y;
    for(int i=2;i<=n;i++)
    {
        int aa=M,bb=a[i],cc=r[i]-ans;
        int gcd=exgcd(aa,bb,x,y);
        if(cc%gcd!=0) return -1;
        x=((cc/gcd*x)%(bb/gcd)+(bb/gcd))%(bb/gcd);
        ans+=x*M;
        M=M/gcd*bb;
        ans%=M;
    }
    return (ans%M+M)%M;
}

int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=1;i<=n;i++)a[i]=read(),r[i]=read();
        printf("%lld\n",china());
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/niiick/article/details/80452379