結果

問題 No.3 ビットすごろく
ユーザー shi-mo
提出日時 2016-03-27 23:30:39
言語 Ruby
(3.4.1)
結果
AC  
実行時間 180 ms / 5,000 ms
コード長 495 bytes
コンパイル時間 240 ms
コンパイル使用メモリ 7,552 KB
実行使用メモリ 14,336 KB
最終ジャッジ日時 2024-07-01 07:48:15
合計ジャッジ時間 5,610 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 33
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #

n = gets.to_i

$nmoves = []
$bc = []

def bitcount(i)
  $bc[i] ||= i.to_s(2).count('1')
end

def move_from(i, n)
  return unless $nmoves[i]

  [i + bitcount(i), i - bitcount(i)].each do |neighbor|
    next if (neighbor < 1) || (n < neighbor)

    nm_neighbor = $nmoves[i] + 1
    next if $nmoves[neighbor] && $nmoves[neighbor] <= nm_neighbor

    $nmoves[neighbor] = nm_neighbor
    move_from(neighbor, n)
  end
end

$nmoves[1] = 1
1.upto(n-1) do |i|
  move_from(i, n)
end
puts $nmoves[n] || -1
0