結果

問題 No.3 ビットすごろく
コンテスト
ユーザー tana_twtr
提出日時 2016-10-30 17:57:30
言語 Ruby
(4.0.2)
コンパイル:
ruby -w -c _filename_
実行:
ruby _filename_
結果
WA  
実行時間 -
コード長 1,189 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 71 ms
コンパイル使用メモリ 9,088 KB
実行使用メモリ 17,792 KB
最終ジャッジ日時 2026-05-19 05:07:52
合計ジャッジ時間 23,934 ms
ジャッジサーバーID
(参考情報)
judge2_1 / judge3_1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 10 WA * 8 TLE * 2 -- * 13
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #
raw source code

def main
    
    n = STDIN.readline.chomp.to_i
    table_forward, table_back = init_table(n)
    count = sugoroku(n, n, 1, table_forward, table_back, [])
    puts count < n ? count : -1

end

def init_table(n)

    table_forward = []
    table_back = []

    1.upto(n) do |i|

        table_forward[i] = i + bitcount(i)
        table_back[i] = i - bitcount(i)

    end

    [table_forward, table_back]

end

def sugoroku(n, goal, count, table_forward, table_back, visited)

    ret = n

    if count >= n
        return ret
    elsif goal == 1
        return count
    end

    visited[goal] = true

    1.upto(goal - 1) do |i|
        if visited[i] == nil && table_forward[i] == goal
            ret_tmp = sugoroku(n, i, count + 1, table_forward, table_back, visited)
            ret = ret_tmp if ret_tmp < ret
        end
    end

    n.downto(goal + 1) do |i|
        if visited[i] == nil && table_back[i] == goal
            ret_tmp = sugoroku(n, i, count + 1, table_forward, table_back, visited)
            ret = ret_tmp if ret_tmp < ret
        end
    end

    ret

end

def bitcount(n)

    count = 0
    n.bit_length.times {|i| count += 1 if n[i] == 1}
    count

end

main()


0