結果

問題 No.187 中華風 (Hard)
ユーザー kotatsugamekotatsugame
提出日時 2020-09-17 04:11:22
言語 Ruby
(3.2.2)
結果
AC  
実行時間 127 ms / 3,000 ms
コード長 1,039 bytes
コンパイル時間 38 ms
コンパイル使用メモリ 11,600 KB
実行使用メモリ 23,500 KB
最終ジャッジ日時 2023-09-04 04:57:52
合計ジャッジ時間 3,864 ms
ジャッジサーバーID
(参考情報)
judge12 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 89 ms
15,252 KB
testcase_01 AC 86 ms
15,356 KB
testcase_02 AC 101 ms
17,420 KB
testcase_03 AC 101 ms
17,668 KB
testcase_04 AC 123 ms
22,996 KB
testcase_05 AC 127 ms
23,072 KB
testcase_06 AC 123 ms
23,120 KB
testcase_07 AC 123 ms
23,096 KB
testcase_08 AC 124 ms
23,500 KB
testcase_09 AC 123 ms
23,276 KB
testcase_10 AC 123 ms
23,300 KB
testcase_11 AC 121 ms
22,988 KB
testcase_12 AC 123 ms
23,264 KB
testcase_13 AC 85 ms
15,284 KB
testcase_14 AC 86 ms
15,308 KB
testcase_15 AC 99 ms
17,720 KB
testcase_16 AC 99 ms
17,968 KB
testcase_17 AC 82 ms
15,148 KB
testcase_18 AC 84 ms
15,128 KB
testcase_19 AC 83 ms
15,288 KB
testcase_20 AC 114 ms
21,404 KB
testcase_21 AC 84 ms
15,184 KB
testcase_22 AC 125 ms
23,116 KB
testcase_23 AC 84 ms
15,264 KB
testcase_24 AC 84 ms
15,268 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
Main.rb:60: warning: ambiguous first argument; put parentheses or a space even after `-' operator
Syntax OK

ソースコード

diff #

# frozen_string_literal: true

# return [rem, mod] or [0, 0] (if no solution)
def crt(r, m)
  raise ArgumentError if r.size != m.size
  
  n = r.size
  r0, m0 = 0, 1
  n.times{ |i|
    raise ArgumentError if m[i] < 1

    r1, m1 = r[i]%m[i], m[i]
    if m0 < m1 then
      r0, r1 = r1, r0
      m0, m1 = m1, m0
    end

    if m0%m1 == 0 then
      return [0, 0] if r0%m1 != r1
      next
    end

    g, im = inv_gcd(m0, m1)
    u1 = m1/g
    return [0, 0] if (r1-r0)%g != 0

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

  return [r0, m0]
end

# internal method
# return [g, x] s.t. g = gcd(a, b), x*a = g (mod b), 0 <= x < b/g
def inv_gcd(a, b)
  a %= b
  return [b, 0] if a == 0

  s, t = b, a
  m0, m1 = 0, 1
  while t>0 do
    u, s = s.divmod(t)
    m0 -= m1*u
    s, t = t, s
    m0, m1 = m1, m0
  end
  m0 += b/s if m0 < 0
  return [s, m0]
end

gets
r, m = $<.map{ |e| e.split.map &:to_i }.transpose

r, m = crt(r, m)

if r == 0 && m == 0
  puts -1
else
  r = m if r == 0
  puts r % (10**9+7)
end
0