結果

問題 No.186 中華風 (Easy)
ユーザー uafr_csuafr_cs
提出日時 2016-02-18 21:16:58
言語 Java21
(openjdk 21)
結果
AC  
実行時間 121 ms / 2,000 ms
コード長 1,848 bytes
コンパイル時間 2,925 ms
コンパイル使用メモリ 74,496 KB
実行使用メモリ 56,348 KB
最終ジャッジ日時 2023-09-27 00:48:42
合計ジャッジ時間 6,203 ms
ジャッジサーバーID
(参考情報)
judge15 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 118 ms
55,776 KB
testcase_01 AC 115 ms
55,512 KB
testcase_02 AC 116 ms
56,148 KB
testcase_03 AC 113 ms
55,932 KB
testcase_04 AC 118 ms
55,736 KB
testcase_05 AC 115 ms
53,784 KB
testcase_06 AC 114 ms
55,952 KB
testcase_07 AC 118 ms
55,824 KB
testcase_08 AC 118 ms
55,756 KB
testcase_09 AC 118 ms
55,912 KB
testcase_10 AC 115 ms
55,760 KB
testcase_11 AC 115 ms
55,984 KB
testcase_12 AC 119 ms
56,348 KB
testcase_13 AC 117 ms
55,916 KB
testcase_14 AC 116 ms
56,188 KB
testcase_15 AC 117 ms
56,096 KB
testcase_16 AC 119 ms
55,708 KB
testcase_17 AC 119 ms
56,160 KB
testcase_18 AC 119 ms
56,176 KB
testcase_19 AC 121 ms
55,676 KB
testcase_20 AC 116 ms
55,448 KB
testcase_21 AC 118 ms
55,736 KB
testcase_22 AC 115 ms
55,752 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.Arrays;
import java.util.Scanner;

class Scratch {

	public static long mod_inv(long a, long m){
		return (a == 1 ? 1 : (1 - m*mod_inv(m%a, a)) / a + m);
	}

	public static long gcd(long a, long b){
		return b == 0 ? a : gcd(b, a % b);
	}

	public static boolean make_so(long[] as, long[] ms){
		for(int fst = 0; fst < ms.length; fst++){
			for(int snd = fst + 1; snd < ms.length; snd++){
				long gcd = gcd(ms[fst], ms[snd]);
				if(gcd == 1){ continue; }

				if(as[fst] % gcd != as[snd] % gcd){
					return false;
				}

				ms[fst] /= gcd;
				ms[snd] /= gcd;
				while(true){
					long gt = gcd(ms[fst], gcd);
					if(gt == 1){ break; }

					ms[fst] *= gt;
					gcd /= gt;
				}
				ms[snd] *= gcd;

				as[fst] %= ms[fst];
				as[snd] %= ms[snd];
			}
		}

		return true;
	}

	public static long chinese_remainder(long[] as, long[] ms){
		long prod = 1, sum = 0;
		long v = 0;

		for(int i = 0; i < ms.length; i++){
			long sub = as[i] - (sum % ms[i]);
			if(sub < 0){ sub += ms[i]; }

			v = (sub * mod_inv(prod, ms[i])) % ms[i];

			sum += (v * prod);
			prod *= ms[i];
		}

		return sum;
	}

	public static void main(String[] args) {
		try (Scanner sc = new Scanner(System.in)) {
			final long x1 = sc.nextLong();
			final long y1 = sc.nextLong();
			final long x2 = sc.nextLong();
			final long y2 = sc.nextLong();
			final long x3 = sc.nextLong();
			final long y3 = sc.nextLong();

			long[] as = new long[]{x1, x2, x3};
			long[] ms = new long[]{y1, y2, y3};
			final boolean so = make_so(as, ms);
			//System.out.println(Arrays.toString(as));
			//System.out.println(Arrays.toString(ms));
			if(!so){
				System.out.println(-1);
				return;
			}

			long prod = 1;
			for(final long p : ms){
				prod *= p;
			}

			final long ret = chinese_remainder(as, ms);
			System.out.println(ret == 0 ? prod : ret);
		}
	}
}
0