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;
    }
  • 相关阅读:
    PyCharm安装及其使用
    web端自动化——Selenium3+python自动化(3.7版本)-chrome67环境搭建
    Unittest单元测试框架
    selenium IDE下载安装(For Chrome and firefox)
    视频上传测试点
    web端自动化——自动化测试准备工作
    selenium3+Python3+sublime text3自动化登录
    Sublime Text3安装及常用插件安装
    web端自动化——selenium3用法详解
    Selenium2+python自动化2.7-火狐44版本环境搭建(转)
  • 原文地址:https://www.cnblogs.com/zzyh/p/7681333.html
Copyright © 2011-2022 走看看