poj 2891Strange Way to Express Integers 中国剩余定理(不互质) 数据没读完就结束了程序居然是runtime error。

来源:互联网 发布:c语言入门书籍下载 编辑:程序博客网 时间:2024/04/28 20:33

Strange Way to Express Integers
Time Limit: 1000MS Memory Limit: 131072KTotal Submissions: 15245 Accepted: 5018

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

Hint

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


#include<cstdio>#include<iostream>using namespace std;#define ll long longll g;void exgcd(ll a,ll b,ll& x,ll& y){    if(b==0)    {        g=a;        x=1;        y=0;    }    else    {        exgcd(b,a%b,y,x);        y-=x*(a/b);    }}int main(){    ll n,a,m,mt,att,k1,k2,c;    while(cin>>n)    {        int flag=0;        cin>>m>>a;        for(int i=1; i<n; i++)        {            cin>>mt>>att;            if(flag) continue;            c=att-a;            exgcd(m,mt,k1,k2);            if(c%g)            {                flag=1;                cout<<-1<<endl;                continue;            }            k1=k1*c/g;            k1=(k1+mt/g)%(mt/g);            a=k1*m+a;            m=m*mt/g;        }        if(!flag)        {            a=(a+m)%m;            if(a)                cout<<a<<endl;            else                cout<<m<<endl;        }    }    return 0;}


1 0
原创粉丝点击