結果

問題 No.187 中華風 (Hard)
ユーザー Takahiro INOUETakahiro INOUE
提出日時 2019-06-05 17:13:26
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
RE  
実行時間 -
コード長 1,349 bytes
コンパイル時間 404 ms
コンパイル使用メモリ 12,032 KB
実行使用メモリ 10,324 KB
最終ジャッジ日時 2023-10-22 01:29:37
合計ジャッジ時間 2,282 ms
ジャッジサーバーID
(参考情報)
judge11 / judge9
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 RE -
testcase_01 RE -
testcase_02 RE -
testcase_03 RE -
testcase_04 RE -
testcase_05 RE -
testcase_06 RE -
testcase_07 RE -
testcase_08 RE -
testcase_09 RE -
testcase_10 RE -
testcase_11 RE -
testcase_12 RE -
testcase_13 RE -
testcase_14 RE -
testcase_15 RE -
testcase_16 RE -
testcase_17 RE -
testcase_18 RE -
testcase_19 RE -
testcase_20 RE -
testcase_21 RE -
testcase_22 RE -
testcase_23 RE -
testcase_24 RE -
権限があれば一括ダウンロードができます

ソースコード

diff #

from functools import reduce

def gcd(a, b):
    while b:
        a, b = b, a%b
    return a

def lcm(a, b):
	return a * b // gcd (a, b)

def extended_euclid(a, b):
    x1, y1, m = 1, 0, a
    x2, y2, n = 0, 1, b
    while m % n != 0:
        q, r = divmod(m, n)
        x1, y1, m, x2, y2, n = x2, y2, n, x1 - q * x2, y1 - q * y2, r
    return (x2, y2, n)

def fraenkel(A, M):
    '''
        solve
            x \equiv a_1 (mod m_1), ... x \equiv a_k (mod m_k)
        by applying the Fraenkel's Algorithm
        Input: 
            A = [a_1, ..., a_k]: a list
            M = [m_1, ..., m_k]: a list.
        Output:
            Returns the tuple (x, mod) of the solution x and the modulus mod = m_1 ... m_k if exists
            else (0, -1).
    '''
    # initialize
    x = 0
    mod = 1
    for a, m in zip(A, M):
        s, _, g = extended_euclid(mod, m)
        q, r = divmod(a - x, g)
        if r != 0:
            return (0, -1)
        temp = m // g
        u = (q * s) % (temp)
        x += mod * u
        mod *= temp
        x %= mod
    return (x, mod)

N = int(input())
MOD = 10**9 + 7
A = []
M = []
for _ in range(N):
    a, m = map(int, input().split())
    A.append(a)
    M.append(m)
x, m = chinese_reminder(A, M)
if (x, m) == (0, -1):
    x = -1
elif x == 0 and m != -1:
    x = reduce(lcm, M)
print(x % MOD if x != -1 else x)
0