結果

問題 No.2119 一般化百五減算
ユーザー gew1fw
提出日時 2025-06-12 14:50:34
言語 PyPy3
(7.3.15)
結果
TLE  
実行時間 -
コード長 1,332 bytes
コンパイル時間 202 ms
コンパイル使用メモリ 82,688 KB
実行使用メモリ 105,088 KB
最終ジャッジ日時 2025-06-12 14:54:26
合計ジャッジ時間 4,775 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 20 TLE * 1 -- * 4
権限があれば一括ダウンロードができます

ソースコード

diff #

import math

def mod_inverse(a, m):
    g, x, y = extended_gcd(a, m)
    if g != 1:
        return None
    else:
        return x % m

def extended_gcd(a, b):
    if b == 0:
        return (a, 1, 0)
    else:
        g, x, y = extended_gcd(b, a % b)
        return (g, y, x - (a // b) * y)

def merge(a1, m1, a2, m2):
    d = a2 - a1
    g = math.gcd(m1, m2)
    if d % g != 0:
        return None
    m = m1 // g
    n = m2 // g
    inv_m = mod_inverse(m, n)
    if inv_m is None:
        return None
    k0 = ((d // g) * inv_m) % n
    new_a = a1 + k0 * m1
    new_mod = m1 * m2 // g
    new_a = new_a % new_mod
    return (new_a, new_mod)

def main():
    import sys
    input = sys.stdin.read().split()
    ptr = 0
    N = int(input[ptr])
    ptr += 1
    M = int(input[ptr])
    ptr += 1
    conditions = []
    for _ in range(M):
        B = int(input[ptr])
        C = int(input[ptr + 1])
        ptr += 2
        a = C % B
        conditions.append((B, a))
    
    current_a = 0
    current_mod = 1
    for (B, a) in conditions:
        res = merge(current_a, current_mod, a, B)
        if res is None:
            print("NaN")
            return
        current_a, current_mod = res
    
    r = current_a % current_mod
    if r <= N:
        print(r)
    else:
        print("NaN")

if __name__ == "__main__":
    main()
0