牛客第十场 Han Xin and His Troops 模线性方程组

题目大意

有n个模线性等式,求解
https://ac.nowcoder.com/acm/contest/890/D
代码

import java.util.*;
import java.math.*;
public class Main {
	static BigInteger m[] = new BigInteger[105];
	static BigInteger r[] = new BigInteger[105];
	static BigInteger x,y;
	static BigInteger exgcd(BigInteger a,BigInteger b) {
		if(b.compareTo(BigInteger.ZERO) == 0) {
			x = BigInteger.ONE;
			y = BigInteger.ZERO;
			return a;
		}
		BigInteger d = exgcd(b,a.mod(b));
		BigInteger t = x;
		x = y;
		BigInteger tmp = a.divide(b).multiply(y);
		y = t.subtract(tmp);
		return d;	
	}
	static BigInteger gcd(BigInteger a,BigInteger b) {
		if(b.equals(BigInteger.ZERO)) return a;
		else return gcd(b,a.mod(b));
	}
	public static void main(String[] args) {
		Scanner reader = new Scanner(System.in);
		int n = reader.nextInt();
		BigInteger K = reader.nextBigInteger();
		for(int i = 0;i<n;i++) {
			m[i] = reader.nextBigInteger();
			r[i] = reader.nextBigInteger();
		}
		int f = 0;
	    BigInteger M = m[0];
	    BigInteger R = r[0];
	    for (int i = 1; i < n; i++){
	    	BigInteger d = gcd(M, m[i]);
	    	BigInteger c = r[i].subtract(R);
	        if (c.mod(d).compareTo(BigInteger.ZERO) != 0){
	        	f = 1;
	            System.out.println("he was definitely lying");
	            break;
	            
	        }
	        exgcd(M.divide(d), m[i].divide(d)); 
	        x = ((c.divide(d)).multiply(x)).mod(m[i].divide(d));
	        R = R.add(x.multiply(M));
	        M = (M.divide(d)).multiply(m[i]);
	        R = R.mod(M);
	    }
	    if (R.compareTo(BigInteger.ZERO) == -1){
	         R = R.add(M);
	    }
	    if(f == 0) {
	    	if(R.compareTo(K) == 1) {
		    	System.out.println("he was probably lying");
		    }
		    else System.out.println(R);
	    }
	}
}

你可能感兴趣的:(数论,模线性方程组,题解)