結果

問題 No.186 中華風 (Easy)
ユーザー keitel339keitel339
提出日時 2021-03-02 22:56:22
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 40 ms / 2,000 ms
コード長 1,122 bytes
コンパイル時間 217 ms
コンパイル使用メモリ 82,504 KB
実行使用メモリ 53,624 KB
最終ジャッジ日時 2024-04-14 05:01:29
合計ジャッジ時間 2,016 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 37 ms
53,180 KB
testcase_01 AC 37 ms
53,624 KB
testcase_02 AC 37 ms
53,232 KB
testcase_03 AC 37 ms
52,476 KB
testcase_04 AC 40 ms
52,884 KB
testcase_05 AC 37 ms
52,680 KB
testcase_06 AC 38 ms
52,644 KB
testcase_07 AC 37 ms
52,752 KB
testcase_08 AC 37 ms
52,872 KB
testcase_09 AC 38 ms
52,956 KB
testcase_10 AC 37 ms
52,572 KB
testcase_11 AC 37 ms
53,164 KB
testcase_12 AC 37 ms
52,128 KB
testcase_13 AC 37 ms
52,620 KB
testcase_14 AC 37 ms
53,148 KB
testcase_15 AC 37 ms
53,364 KB
testcase_16 AC 36 ms
52,740 KB
testcase_17 AC 38 ms
53,476 KB
testcase_18 AC 37 ms
52,952 KB
testcase_19 AC 37 ms
53,080 KB
testcase_20 AC 38 ms
52,212 KB
testcase_21 AC 37 ms
52,068 KB
testcase_22 AC 36 ms
52,952 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

def gcd_ext(a, b):   
    '''
    1次不定方程式 ax+by=gcd(a, b) の解と最大公約数を返す。負の値には未対応
    x, y, gcd(a, b)
    '''
    if a < b:
        x, y, s = gcd_ext(b, a)
        return y, x, s
    s, xs, ys = a, 1, 0
    t, xt, yt = b, 0, 1

    while t > 0:
        n = s // t
        s, t = t, s % t
        xs, xt = xt, xs - n * xt
        ys, yt = yt, ys - n * yt
    return xs, ys, s


def crt(b, m):
    '''
    すべてのiについて x≡b[i](mod, m[i]) の論理積を満たす x と lcm(m[:]) を求める。
    解がない場合 -1, 0 を返す
    '''
    n = len(b)
    assert n == len(m)
    m0, b0 = 1, 0
    for i in range(n):
        m1, b1 = m[i], b[i] % m[i]
        p, _, d = gcd_ext(m0, m1) # m0 * p + m1 * q = gcd(m0, m1)
        if (b1 - b0) % d: # b0 ≡ b1 (mod gcd(m0, m1)) の不成立
            return -1, 0
        lcm = m0 * m1 // d
        b0 = (b0 + (b1 - b0) // d * p * m0) % lcm
        m0 = lcm
    return b0, lcm

import sys
xy = list(map(int, sys.stdin.read().split()))
x = xy[0::2]
y = xy[1::2]
ans, lcm = crt(x, y)
print(ans if ans else lcm)
0