結果

問題 No.3 ビットすごろく
ユーザー phantomilephantomile
提出日時 2015-12-19 07:49:12
言語 Python3
(3.13.1 + numpy 2.2.1 + scipy 1.14.1)
結果
AC  
実行時間 43 ms / 5,000 ms
コード長 1,126 bytes
コンパイル時間 75 ms
コンパイル使用メモリ 12,544 KB
実行使用メモリ 11,648 KB
最終ジャッジ日時 2024-07-01 07:38:25
合計ジャッジ時間 2,248 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 33
権限があれば一括ダウンロードができます

ソースコード

diff #

"""
Yukicoder No.3 ビットすごろく

author: yamaton
date: 2015-12-18
"""

import itertools as it
import functools
import operator
import collections
import math
import sys


def bitcount(n):
    res = 0
    while n > 0:
        res += n & 1
        n >>= 1
    return res


def solve(n):
    if n == 1:
        return 1
    q = collections.deque()
    q.append(1)
    path_to = dict()
    path_to[1] = None

    while q:
        curr = q.popleft()
        delta = bitcount(curr)
        for next_ in (curr + delta, curr - delta):
            if next_ not in path_to and 1 <= next_ <= n:
                q.append(next_)
                path_to[next_] = curr
            if next_ == n:
                # pp(path_to)
                return steps_from_start(path_to, n)
    else:
        return -1

def steps_from_start(path_to, n, start=1):
    cnt = 1
    while n != start:
        n = path_to[n]
        cnt += 1
    return cnt


def pp(*args, **kwargs):
    return print(*args, file=sys.stderr, **kwargs)


def main():
    n = int(input())
    result = solve(n)
    print(result)


if __name__ == '__main__':
    main()
0