牛客第十场 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);
	    }
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值