zoukankan      html  css  js  c++  java
  • Strange Way to Express Integers(扩展欧几里得解同余方程)

     

    时间限制(普通/Java):1000MS/10000MS     内存限制:65536KByte
    总提交: 55            测试通过:26

    描述

     

    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, …, akare 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?

    输入

     

    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 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.

    样例输入

     

    样例输出

     

    提示

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

    题目来源

    POJ Monthly 2006.7

     

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <algorithm>
     4 #define ll long long
     5 using namespace std;
     6 
     7 ll exgcd(ll a,ll b,ll &x,ll &y)
     8 {
     9     if(b==0){
    10         x=1,y=0;
    11         return a;
    12     }
    13     ll r=exgcd(b,a%b,x,y);
    14     ll t=x;
    15     x=y,y=t-a/b*y;
    16     return r;
    17 }
    18 
    19 int main()
    20 {
    21     ll n,a1,r1,a2,r2,ans,a,b,c,d,x0,y0;
    22     while(scanf("%lld",&n)!=EOF){
    23         int flag=1;
    24         scanf("%lld%lld",&a1,&r1);
    25         for(ll i=1;i<n;i++){
    26             scanf("%lld%lld",&a2,&r2);
    27             a=a1,b=a2,c=r2-r1;
    28             ll d=exgcd(a,b,x0,y0);
    29             if(c%d!=0){//不存在可能值
    30                 flag=0;
    31             }
    32             int t=b/d;
    33             x0=(x0*(c/d)%t+t)%t;//x0为正
    34             r1=a1*x0+r1;
    35             a1=a1*(a2/d);
    36         }
    37         if(!flag){
    38             printf("-1
    ");
    39         }
    40         else{
    41             printf("%lld
    ",r1);
    42         }
    43     }
    44     return 0;
    45 }

     

     

  • 相关阅读:
    非线性方程(组):高维方程解法
    非线性方程(组):一维非线性方程(二)插值迭代方法 [MATLAB]
    非线性方程(组):一维非线性方程(一)二分法、不动点迭代、牛顿法 [MATLAB]
    非线性方程(组):计算基本理论
    常微分方程初值问题:多步预测-修正方法 [MATLAB]
    你会使用super()吗?你确定你了解它吗?
    Django简介
    Web框架的原理
    Django ORM 中的批量操作
    Python的切片
  • 原文地址:https://www.cnblogs.com/ChangeG1824/p/10726247.html
Copyright © 2011-2022 走看看