yukicoder 186/187 中華風

2015/04/20 (Mon) yukicoder 数学 中国剰余定理

問題

Easy Hard

方針

正しい(?)方針は名前の通り中国剰余定理だが…

非負整数のベクトル $ \mathbf{a} , \mathbf{b} $, 正整数のベクトル $ \mathbf{m} $ について $ \mathbf{a}_i x \equiv \mathbf{b}_i \mod \mathbf{m}_i $ のような形をした方程式を線形連立合同式と言う。 ただし今は $ \mathbf{a}_i = 1 $ である。

これの解き方は蟻本 261 ページを参照。 $ \mathbf{m}_i $ の LCM は非常に大きくなりうるので多倍長が使える言語で実装する必要がある。

実装

Ruby による

def extgcd(a, b)
  if b.zero?
    {x: 1, y: 0, gcd: a}
  else
    prev = extgcd(b, a % b)
    {
      x: prev[:y],
      y: prev[:x] - (a / b) * prev[:y],
      gcd: prev[:gcd]
    }
  end
end

def mod_inv(a,m)
  res = extgcd(a,m)
  x = res[:x]
  (m+x%m)%m
end

def linear_congruence(as,bs,ms)
  x,m = 0,1
  as.size.times do |i|
    a = as[i]*m
    b = bs[i] - as[i] * x
    d = ms[i].gcd(a)
    return if b % d != 0
    t = b/d * mod_inv(a/d, ms[i]/d) % (ms[i]/d)
    x = x + m*t
    m *= ms[i]/d
  end
  [x%m, m]
end

n = gets.to_i
t = []
n.times do
  x,y = gets.chomp.split.map(&:to_i)
  t << [x,y]
end
xs,ys = t.transpose

as = [1] * n

mod = 1000000007
ans = linear_congruence(as,xs,ys)
puts ->(x){
  if x.nil?
    -1
  elsif ans[0] == 0
    ans[1] % mod
  else
    ans[0] % mod
  end
}.call(ans)