2019牛客暑期多校訓練營(第十場)D Han Xin and His Troops(Java大數+擴展中國剩餘定理模板)

鏈接:https://ac.nowcoder.com/acm/contest/890/D

題意:求同餘方程組。

思路:

import java.math.BigInteger;
import java.util.Scanner;
 
 
public class Main {
     
    public static int N = 100010;
    public static BigInteger a[] = new BigInteger[N];
    public static BigInteger m[] = new BigInteger[N];  
    public static int k;
    public static BigInteger mm,xx,yy;
    public static BigInteger exgcd(BigInteger a,BigInteger b){
        if(b.compareTo(BigInteger.ZERO)==0){
            xx=BigInteger.ONE;
            yy=BigInteger.ZERO;
            return a;
        }
        BigInteger z,d=exgcd(b,a.mod(b));
        z=xx;
        xx=yy;
        yy=z.subtract(a.divide(b).multiply(yy));
        return d;
    }
    public  static BigInteger china(){
        BigInteger c,d,ans=a[1],M=m[1];
        for(int i=2;i<=k;i++){
             c=(a[i].subtract(ans.mod(m[i]).add(m[i])).mod(m[i]));
              
             d=exgcd(M,m[i]);
              
             if(c.mod(d).compareTo(BigInteger.ZERO)!=0) return new BigInteger("-1");
             xx=xx.multiply(c.divide(d)).mod(m[i].divide(d));
             ans=ans.add(xx.multiply(M));
             M=M.multiply(m[i].divide(d));
             ans=ans.mod(M).add(M).mod(M);
        }
        return ans;
    }
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in );
        k=cin.nextInt(); mm=cin.nextBigInteger();
        for(int i=1;i<=k;i++){
            m[i]=cin.nextBigInteger();
            a[i]=cin.nextBigInteger();
        }
        BigInteger pm=china(),fu1=new BigInteger("-1");
         
        if(pm.compareTo(fu1)==0) System.out.println("he was definitely lying");
        else if(pm.compareTo(mm)>0) System.out.println("he was probably lying");
        else System.out.println(pm);
    }
     
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章