結果

問題 No.3 ビットすごろく
ユーザー tshigitshigi
提出日時 2016-08-01 12:16:30
言語 Ruby
(3.3.0)
結果
AC  
実行時間 129 ms / 5,000 ms
コード長 766 bytes
コンパイル時間 350 ms
コンパイル使用メモリ 11,536 KB
実行使用メモリ 27,220 KB
最終ジャッジ日時 2023-09-14 00:04:25
合計ジャッジ時間 5,602 ms
ジャッジサーバーID
(参考情報)
judge14 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 83 ms
15,168 KB
testcase_01 AC 84 ms
15,216 KB
testcase_02 AC 82 ms
15,284 KB
testcase_03 AC 91 ms
18,648 KB
testcase_04 AC 85 ms
15,680 KB
testcase_05 AC 104 ms
21,104 KB
testcase_06 AC 94 ms
18,736 KB
testcase_07 AC 90 ms
16,988 KB
testcase_08 AC 99 ms
19,788 KB
testcase_09 AC 114 ms
22,660 KB
testcase_10 AC 117 ms
23,644 KB
testcase_11 AC 109 ms
21,828 KB
testcase_12 AC 105 ms
20,964 KB
testcase_13 AC 93 ms
17,844 KB
testcase_14 AC 118 ms
23,744 KB
testcase_15 AC 128 ms
27,164 KB
testcase_16 AC 123 ms
25,792 KB
testcase_17 AC 126 ms
27,116 KB
testcase_18 AC 88 ms
17,052 KB
testcase_19 AC 125 ms
27,116 KB
testcase_20 AC 84 ms
15,248 KB
testcase_21 AC 82 ms
15,148 KB
testcase_22 AC 115 ms
23,864 KB
testcase_23 AC 126 ms
27,088 KB
testcase_24 AC 128 ms
27,128 KB
testcase_25 AC 129 ms
27,220 KB
testcase_26 AC 82 ms
15,348 KB
testcase_27 AC 92 ms
18,480 KB
testcase_28 AC 125 ms
25,880 KB
testcase_29 AC 111 ms
22,432 KB
testcase_30 AC 85 ms
15,224 KB
testcase_31 AC 85 ms
15,160 KB
testcase_32 AC 110 ms
21,940 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #

inputs = STDIN.readlines.map(&:chomp)
N = inputs[0].to_i

class Koma
  def initialize(pos)
    @pos = pos
  end

  attr_reader :pos

  def ==(other)
    @pos == other.pos
  end

  def valid?
    1 <= @pos && @pos <= N
  end

  def goal?
    @pos == N
  end

  def next_cands
    ons = @pos.to_s(2).count('1')
    [Koma.new(@pos + ons), Koma.new(@pos - ons)].select(&:valid?)
  end
end

def search
  queue = [[Koma.new(1)]]
  visited = { 1 => true }
  until queue.empty?
    path = queue.shift
    cands = path.last.next_cands.reject { |cand| visited[cand.pos] }
    return path.size + 1 if cands.any?(&:goal?)
    queue.push(*cands.map { |cand| path + [cand] })
    visited.update(cands.map { |cand| [cand.pos, true] }.to_h)
  end
  -1
end

puts N == 1 ? 1 : search
0