Strange Way to Express Integers--扩展欧几里得和中国剩余定理

来源:互联网 发布:海岛奇兵医师数据 编辑:程序博客网 时间:2024/05/29 11:30

Strange Way to Express Integers
Time Limit: 1000MS Memory Limit: 131072KTotal Submissions: 14124 Accepted: 4570

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 a1a2…, ak. For some non-negative m, divide it by every ai (1 ≤ i ≤ k) to find the remainder ri. If a1a2, …, ak are properly chosen, m can be determined, then the pairs (airi) 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 airi (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

28 711 9

Sample Output

31
题目链接:http://poj.org/problem?id=2891


这个题好啊,终于让我搞懂了为什么扩欧可以求逆元了,填上了以前的一个漏洞,以前都是直接上板子,这感觉,爽!

这个题就是个裸的中国剩余定理,题意是说有k组数,满足x%m[i]=a[i],求最小整数解。注意是最小


这个题,怎么说呢,我还是用代码讲吧。


代码:

#include <cstdio>#include <cstring>#include <iostream>using namespace std;long long exGCD(long long a,long long b,long long &x,long long &y)//扩展欧几里得{    if(b==0)    {        x=1;        y=0;        return a;//最大公约数    }    long long d=exGCD(b,a%b,x,y);    long long tmp=x;//扩欧的公式,推出来的结论    x=y;    y=tmp-a/b*y;    return d;//最大公约数}int main(){    int n;    long long a1,r1,a2,r2;    long long c,d,x,y;    while(~scanf("%d",&n))    {        bool flag=false;//标记变量        cin>>a1>>r1;        for(int i=0;i<n-1;i++)        {            cin>>a2>>r2;            if(flag)                continue;            c=r2-r1;//相当于gcd(a,b);            d=exGCD(a1,a2,x,y);//因为不保证互质,所以要一组组算            if(c%d)//扩欧无解            {                //printf("%d %d\n",c,d);                flag=true;                continue;            }            x*=c/d;//x为乘法逆元            a2/=d;            x=(x%a2+a2)%a2;            r1=r1+x*a1;//最小            a1*=a2;        }        if(flag)            printf("-1\n");        else            cout<<r1<<endl;    }    return 0;}


可能有好多人看不懂,没关系,我放三个大神的链接,保证明白!

http://blog.csdn.net/u010468553/article/details/38346195

中国剩余定理

http://blog.csdn.net/forpro_yang/article/details/6666089

讲解这个题,很详细

http://blog.csdn.net/lin375691011/article/details/38443865

这个比较适合我


继续加油吧!


0 0