zoukankan      html  css  js  c++  java
  • 2018年全国多校算法寒假训练营练习比赛(第三场)B.一个小问题(中国剩余定理)

    链接:https://www.nowcoder.net/acm/contest/75/B
    来源:牛客网

    uu遇到了一个小问题,可是他不想答。你能替他解决这个问题吗?
    问题:给你k对a和r是否存在一个正整数x使每队a和r都满足:x mod a=r,求最小正解x或无解。

    输入描述:

    第一行是正整数k(k<=100000)
    接下来k行,每行有俩个正整数a,r(100000>a>r>=0)

    输出描述:

    在每个测试用例输出非负整数m,占一行。
    如果有多个可能的值,输出最小的值。
    如果没有可能的值,则输出-1。

    示例1

    输入

    2
    8 7
    11 9

    输出

    31

    中国剩余定理的非互素模板题
    #include<iostream> 
    #include<cstring> 
    #include<cstdio>
    #include<cmath>
    #include<algorithm>
    using namespace std;
    typedef long long LL;
    LL exgcd(LL a,LL b,LL &x, LL &y)
    {
      if(b==0)
      {
          x=1;
          y=0;
          return a;
      }
        LL r=exgcd(b,a%b,x,y);
        LL t=x;
        x=y;
        y=t-a/b*y;
        return r;
    }
    int main()
    {
        LL flag=1;
        LL k,nowa,nowr,a,r,x,y,gc,ans,tmp;
        cin>>k;
        cin>>nowa;
        cin>>nowr;
        for(int i=2;i<=k;i++)
        {
            cin>>a>>r;
            if(flag==0)
            continue;
            gc=exgcd(nowa,-a,x,y);
            if((r-nowr)%gc!=0)
            {
                flag=0;
                continue;
            }
            x=x*(r-nowr)/gc;
            tmp=(-a)/gc;
            x=(x%tmp+tmp)%tmp;
            nowr=nowa*x+nowr;
            nowa=nowa*(-a)/gc;
        }
        if(flag==0)
        {
          puts("-1");
          return 0;
        }
        else
        {
            if(nowa<0)
            nowa=-nowa;
            ans=(nowr%nowa+nowa)%nowa;
            if(ans==0)
            ans+=nowa;
            cout<<ans<<endl;
        }
        return 0;
    }


  • 相关阅读:
    mybatis-plus 插件
    mybatis-plus 逆向工程模板
    mybatis-plus 使用
    response.getWriter()
    String.length()和String.getBytes().length
    mybatis 中有趣的符号#与$
    html动画实现
    把我坑惨的一个update语句
    我们为什么不用 Select * 吗?
    Java 正则表达式
  • 原文地址:https://www.cnblogs.com/a249189046/p/8418243.html
Copyright © 2011-2022 走看看