結果

問題 No.3 ビットすごろく
ユーザー shinjiweb
提出日時 2016-08-27 22:09:46
言語 Ruby
(3.4.1)
結果
AC  
実行時間 117 ms / 5,000 ms
コード長 473 bytes
コンパイル時間 207 ms
コンパイル使用メモリ 7,552 KB
実行使用メモリ 12,544 KB
最終ジャッジ日時 2024-07-01 08:03:05
合計ジャッジ時間 4,765 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 33
権限があれば一括ダウンロードができます
コンパイルメッセージ
Main.rb:15: warning: ambiguous first argument; put parentheses or a space even after `-' operator
Syntax OK

ソースコード

diff #

def bits(n)
  count = 0
  while n > 0
    count += n % 2
    n /= 2
  end
  count
end
n = gets.to_i
queue = [[1, 1]]
visited = Array.new(n + 1)
loop do
  head = queue.shift
  if head.nil?
    puts -1
    break
  end
  position, distance = head
  if position == n
    puts distance
    break
  end
  b = bits(position)
  [position + b, position - b].each do |p|
    queue << [p, distance + 1] unless p < 0 || p > n || visited[position] == 1
  end
  visited[position] = 1
end
0