zoukankan      html  css  js  c++  java
  • POJ2891 Strange Way to Express Integers(中国剩余定理)

    Strange Way to Express Integers
    Time Limit: 1000MS   Memory Limit: 131072K
    Total Submissions: 14626   Accepted: 4787

    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

    2
    8 7
    11 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.

    Source

     1 #include "bits/stdc++.h"
     2 using namespace std;
     3 typedef long long LL;
     4 const int MAX=10005;
     5 LL cas;
     6 LL n;
     7 LL aa[MAX],r[MAX];
     8 LL exgcd(LL a,LL b,LL &x,LL &y){
     9     if (b==0){x=1,y=0;return a;}
    10     LL d=exgcd(b,a%b,x,y),t=x;x=y,y=t-(a/b)*y;
    11     return d;
    12 }
    13 LL modeqset(){
    14     LL i,j;
    15     LL a,b,c,d,x,y,t;
    16     for (i=2;i<=n;i++){
    17         a=aa[i-1],b=aa[i];
    18         c=r[i]-r[i-1];
    19         d=exgcd(a,b,x,y);
    20         if (c%d) return -1;
    21         t=b/d;
    22         x=(x*(c/d)%t+t)%t;
    23         r[i]=r[i-1]+aa[i-1]*x;
    24         aa[i]=aa[i]/d*aa[i-1];
    25     }
    26     return r[n];
    27 }
    28 int main(){
    29     freopen ("way.in","r",stdin);
    30     freopen ("way.out","w",stdout);
    31     LL i,j;
    32     while (~scanf("%lld",&n)){
    33         for (i=1;i<=n;i++)
    34          scanf("%lld%lld",aa+i,r+i);
    35         LL ans=modeqset();
    36         printf("%lld\n",ans);
    37     }
    38     return 0;
    39 }
    未来是什么样,未来会发生什么,谁也不知道。 但是我知道, 起码从今天开始努力, 肯定比从明天开始努力, 要快一天实现梦想。 千里之行,始于足下! ——《那年那兔那些事儿》
  • 相关阅读:
    [apue] FIFO:不是文件的文件
    [apue] 等待子进程的那些事儿
    [apue] popen/pclose 疑点解惑
    [apue] 使用 popen/pclose 的一点疑问
    [apue] 使用 poll 检测管道断开
    [apue] dup2的正确打开方式
    [apue] 管道原子写入量的一个疑问
    [apue] 测试管道容量的一些疑问
    【新阁教育】再也不用担心我的PLC通信不上了
    【新阁教育】三菱PLC的这个功能,真的很强大
  • 原文地址:https://www.cnblogs.com/keximeiruguo/p/6014003.html
Copyright © 2011-2022 走看看