結果

問題 No.187 中華風 (Hard)
ユーザー kokonotsukokonotsu
提出日時 2024-05-06 20:36:13
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 95 ms / 3,000 ms
コード長 1,747 bytes
コンパイル時間 101 ms
コンパイル使用メモリ 12,800 KB
実行使用メモリ 11,008 KB
最終ジャッジ日時 2024-05-06 20:36:16
合計ジャッジ時間 2,400 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 28 ms
10,880 KB
testcase_01 AC 28 ms
10,752 KB
testcase_02 AC 50 ms
10,880 KB
testcase_03 AC 55 ms
10,752 KB
testcase_04 AC 88 ms
11,008 KB
testcase_05 AC 87 ms
10,752 KB
testcase_06 AC 91 ms
10,752 KB
testcase_07 AC 89 ms
11,008 KB
testcase_08 AC 95 ms
10,880 KB
testcase_09 AC 87 ms
10,880 KB
testcase_10 AC 92 ms
10,752 KB
testcase_11 AC 82 ms
11,008 KB
testcase_12 AC 81 ms
11,008 KB
testcase_13 AC 29 ms
10,752 KB
testcase_14 AC 28 ms
10,880 KB
testcase_15 AC 50 ms
10,880 KB
testcase_16 AC 50 ms
10,880 KB
testcase_17 AC 25 ms
10,752 KB
testcase_18 AC 27 ms
10,880 KB
testcase_19 AC 25 ms
10,752 KB
testcase_20 AC 69 ms
11,008 KB
testcase_21 AC 25 ms
10,624 KB
testcase_22 AC 81 ms
10,880 KB
testcase_23 AC 26 ms
10,624 KB
testcase_24 AC 26 ms
10,624 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

def ext_gcd(a, b):
    """
    一次不定方程式 ax + by = d(=gcd(a, b))の特殊解を求める
    :return: x, y, gcd(a, b)をタプルで返す
    """
    # a * x + b * y == d
    ret_x, ret_y, ret_gcd = 1, 0, a
    x2, y2, d2 = 0, 1, b

    while d2 != 0:
        q = ret_gcd // d2
        ret_gcd, d2 = d2, ret_gcd - d2 * q
        ret_x, x2 = x2, ret_x - x2 * q
        ret_y, y2 = y2, ret_y - y2 * q

    if ret_gcd < 0:
        ret_gcd, ret_x, ret_y = -ret_gcd, -ret_x, -ret_y

    return ret_x, ret_y, ret_gcd

def calc_inv(a, m):
    """
    ax ≡ 1 (mod m)のx(a^(-1))の値を求める
    :return: gcd(a, m),
    """
    inv, _, g = ext_gcd(a, m)

    return g, (inv + m) % m


def Chinese_Remainder_Theorem(r: list, m: list):
    """
    # x ≡ r_i (mod m_i) (0<=i<=n)を満たす連立合同式の解x (mod m0)があれば(x, m0)を返す
    # 解が存在しない場合は(None, None)が返る
    :return:
    """
    n = len(r)
    r0, m0 = 0, 1
    for i in range(n):
        assert 1 <= m[i]
        r1 = r[i] % m[i]
        m1 = m[i]

        if m0 < m1:
            r0, r1 = r1, r0
            m0, m1 = m1, m0

        if m0 % m1 == 0:
            if r0 % m1 != r1:
                return None, None
            continue

        g, im = calc_inv(m0, m1)
        u1 = m1 // g
        if (r1 - r0) % g:
            return None, None

        x = (r1 - r0) // g % u1 * im % u1
        r0 += x * m0
        m0 *= u1
        if r0 < 0:
            r0 += m0

    return r0, m0


N = int(input())
X = []
Y = []
for i in range(N):
    x, y = map(int, input().split())
    X.append(x)
    Y.append(y)

ans, m = Chinese_Remainder_Theorem(X, Y)
if ans == 0:
    ans = m

print(ans % (10 ** 9 + 7) if ans is not None else -1)
0