PKU 2891:Strange Way to Express Integers(中国剩余定理非互质)

来源:互联网 发布:网络选修课网站 编辑:程序博客网 时间:2024/06/05 03:01

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 (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 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 <stdio.h>long long x, y, d;long long  exgcd (long long a, long long b){    if(!b){        x=1;        y=0;        return a;    }    d = exgcd(b, a%b);    long long temp = x;    x = y;    y = temp - a/b*y;    return d;}int main(){    long long k, a1, b1, a2, b2;    bool flag;    while(~scanf("%lld", &k))    {        flag = false;        scanf("%lld%lld", &a1, &b1);        k--;        while(k--)        {            scanf("%lld%lld", &a2, &b2);            if(flag) continue;            d = exgcd(a1, a2);            if((b2-b1)%d){flag = true; continue;}            x *= ((b2-b1)/d);            x = (x%(a2/d)+a2/d)%(a2/d);            b1 = a1*x+b1; a1 = a1/d*a2;        }        if(flag) printf("-1\n");        else printf("%lld\n", b1);    }    return 0;}



0 0