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: 17257   Accepted: 5796

    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.

    题解:中国剩余定理非互素版本

    代码:

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #define LL long long
    #define maxn 100009
    using namespace std;
    
    int n;
    LL m[maxn],r[maxn];
    
    LL exgcd(LL a,LL b,LL &x,LL &y){
        if(b==0){
            x=1;y=0;
            return a;
        }
        LL t,r=exgcd(b,a%b,x,y);
        t=x;x=y;y=t-a/b*y;
        return r;
    }
    
    LL CRT(LL m[],LL r[],LL n){
        LL x,y,gcd,M=m[1],R=r[1];
        for(int i=2;i<=n;i++){
            LL gcd=exgcd(M,m[i],x,y);
            if((r[i]-R)%gcd)return -1;
            x=(r[i]-R)/gcd*x%(m[i]/gcd);
            R+=x*M;//新的余数R=r1+x*m[1] 
            M=M/gcd*m[i];//新的M,lcm(m1,m2) 
            R%=M;
        }
        return R>0?R:R+M;
    }
    
    int main(){
        while(~scanf("%d",&n)){
            for(int i=1;i<=n;i++)
             scanf("%lld%lld",&m[i],&r[i]);
            printf("%lld
    ",CRT(m,r,n));
        }
        return 0;
    }
  • 相关阅读:
    设计模式:生产者消费者模式
    图解SSH原理
    监听Google Player下载并获取包名等信息
    android targetSdkVersion>=26收不到广播的处理
    ant property file刷新不及时
    maven的pom文件报错: must be "pom" but is "jar"
    AJAX其实就是一个异步网络请求
    String、StringBuffer、StringBuilder的区别
    Properties、ResourceBundle
    JavaWeb--Listener
  • 原文地址:https://www.cnblogs.com/zzyh/p/7681333.html
Copyright © 2011-2022 走看看