結果

問題 No.281 門松と魔法(1)
ユーザー yuruhiya
提出日時 2020-10-31 11:44:05
言語 Crystal
(1.14.0)
結果
AC  
実行時間 2 ms / 1,000 ms
コード長 1,165 bytes
コンパイル時間 12,958 ms
コンパイル使用メモリ 296,648 KB
実行使用メモリ 6,944 KB
最終ジャッジ日時 2024-06-30 21:35:31
合計ジャッジ時間 13,223 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 57
権限があれば一括ダウンロードができます

ソースコード

diff #

lib C
  fun strtoll(s : UInt8*, p : UInt8**, b : Int32) : Int64
end

class String
  def to_i64
    C.strtoll(self, nil, 10)
  end
end

INF = 10i64 ** 9

# a -> less than b
def calc(a, b, d)
  if a < b
    {0i64, a}
  else
    res = (a - b) // d + 1
    next_a = {a - res * d, 0i64}.max
    next_a < b ? {res, next_a} : {INF, next_a}
  end
end

def solve(a, b, c, d)
  a, b, c = [a, b, c].map { |i| {i, 0i64}.max }
  if [a, b, c].count { |i| i == 0 } >= 2
    INF
  elsif a == b
    {solve(a - d, b, c, d) + 1, solve(a, b - d, c, d) + 1}.min
  elsif a == c
    {solve(a - d, b, c, d) + 1, solve(a, b, c - d, d) + 1}.min
  elsif b == c
    {solve(a, b - d, c, d) + 1, solve(a, b, c - d, d) + 1}.min
  else
    if (b > a && b > c) || (b < a && b < c)
      0i64
    else
      v1, next_a = calc(a, b, d)
      v2, next_c = calc(c, b, d)
      v3, next_b = calc(b, {a, c}.min, d)
      {v1 + v2 + solve(next_a, b, next_c, d), v3 + solve(a, next_b, c, d)}.min
    end
  end
end

d, a, b, c = (1..4).map { read_line.to_i64 }
if d == 0
  puts (b > a && b > c && a != c) || (b < a && b < c && a != c) ? 0 : -1
else
  ans = solve(a, b, c, d)
  puts ans < INF ? ans : -1
end
0