結果
| 問題 | No.3 ビットすごろく | 
| コンテスト | |
| ユーザー |  | 
| 提出日時 | 2017-02-27 23:40:00 | 
| 言語 | Ruby (3.4.1) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 825 ms / 5,000 ms | 
| コード長 | 1,020 bytes | 
| コンパイル時間 | 70 ms | 
| コンパイル使用メモリ | 7,424 KB | 
| 実行使用メモリ | 135,936 KB | 
| 最終ジャッジ日時 | 2024-07-01 08:33:53 | 
| 合計ジャッジ時間 | 13,237 ms | 
| ジャッジサーバーID (参考情報) | judge5 / judge1 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| other | AC * 33 | 
コンパイルメッセージ
Syntax OK
ソースコード
n = gets.to_i
def to_binary(x)
  binary_str = ''
  until x == 0 || x == 1
    binary_str += (x % 2).to_s
    x /= 2
  end
  binary_str += x.to_s
  binary_str.reverse
end
def get_distance(current)
  to_binary(current).split('').map(&:to_i).inject(:+)
end
def move(histories, n, passed)
  next_histories = histories.map do |history|
    distance = get_distance(history.last)
    [
      history.dup + [history.last + distance],
      history.dup + [history.last - distance]
    ].reject do |new_history|
      next_position = new_history.last
      return new_history if next_position == n
      next true if passed.include?(new_history.last)
      next true if next_position < 1 || next_position > n
      false
    end
  end.flatten(1).uniq {|history| history.last}
  return [] if next_histories.empty?
  passed += next_histories.map(&:last)
  move(next_histories, n, passed)
end
def move_to_goal(n)
  return [1] if n == 1
  move([[1]], n, [])
end
result = move_to_goal(n)
puts result.empty? ? -1 : result.length
            
            
            
        