結果

問題 No.3 ビットすごろく
ユーザー Takuya ItoTakuya Ito
提出日時 2023-12-15 10:03:42
言語 Go
(1.22.1)
結果
AC  
実行時間 2 ms / 5,000 ms
コード長 1,984 bytes
コンパイル時間 11,662 ms
コンパイル使用メモリ 216,344 KB
実行使用メモリ 6,676 KB
最終ジャッジ日時 2023-12-15 10:03:55
合計ジャッジ時間 12,642 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
6,676 KB
testcase_01 AC 1 ms
6,676 KB
testcase_02 AC 2 ms
6,676 KB
testcase_03 AC 1 ms
6,676 KB
testcase_04 AC 1 ms
6,676 KB
testcase_05 AC 1 ms
6,676 KB
testcase_06 AC 1 ms
6,676 KB
testcase_07 AC 1 ms
6,676 KB
testcase_08 AC 1 ms
6,676 KB
testcase_09 AC 2 ms
6,676 KB
testcase_10 AC 2 ms
6,676 KB
testcase_11 AC 2 ms
6,676 KB
testcase_12 AC 2 ms
6,676 KB
testcase_13 AC 2 ms
6,676 KB
testcase_14 AC 1 ms
6,676 KB
testcase_15 AC 2 ms
6,676 KB
testcase_16 AC 1 ms
6,676 KB
testcase_17 AC 2 ms
6,676 KB
testcase_18 AC 2 ms
6,676 KB
testcase_19 AC 2 ms
6,676 KB
testcase_20 AC 1 ms
6,676 KB
testcase_21 AC 1 ms
6,676 KB
testcase_22 AC 1 ms
6,676 KB
testcase_23 AC 1 ms
6,676 KB
testcase_24 AC 2 ms
6,676 KB
testcase_25 AC 2 ms
6,676 KB
testcase_26 AC 1 ms
6,676 KB
testcase_27 AC 1 ms
6,676 KB
testcase_28 AC 1 ms
6,676 KB
testcase_29 AC 2 ms
6,676 KB
testcase_30 AC 1 ms
6,676 KB
testcase_31 AC 2 ms
6,676 KB
testcase_32 AC 2 ms
6,676 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

// 1からNの番号がふられている一直線に並べられているN個のマスがある。
// 1から開始のマスとして、ゴールはNが書かれているマスとする。

// その場に書かれている数字の2進数で表現した時の1のビット数 だけ「前」または「後」に進めることができる。
// (1未満とN+1以上のマスには移動することは出来ない、正確にNにならないとゴールできない)

// 自然数Nを与えられた時、ゴールに到達できる最短の移動数(開始のマスへも移動にカウントする)を求めてください。
// 到達できない場合は-1を出力してください。

// 開始のマスがすでにゴールになっている場合もあリます。

package main

import (
	"fmt"
)

func main() {
	// ゴール
	var n int
	fmt.Scan(&n)

	// ゴールに到達する最短の移動数
	results := make([]int, n+1)
	results[1] = 1 // 開始のマスへも移動にカウントすることから

	que := []int{1}

	visited := make([]bool, n+1)
	visited[0] = true
	visited[1] = true

	for len(que) > 0 {
		// キューの先頭を取り出す
		i := que[0]
		que = que[1:]

		bit := countBits(uint(i))
		if bit == 0 {
			continue
		}

		// 前に進む
		next := i + bit
		if next <= n && !visited[next] {
			if next != n {
				que = append(que, next)
			}
			visited[next] = true
			results[next] = results[i] + 1
		}

		back := i - bit
		if back > 0 && back < n && !visited[back] {
			que = append(que, back)
			visited[back] = true
			results[back] = results[i] + 1
		}
	}

	if results[n] == 0 {
		results[n] = -1
	}

	fmt.Println(results[n])
}

// 数値を2進数に変換した際の'1'の数を返す
func countBits(num uint) int {
	count := 0
	for num > 0 {
		count += int(num & 1) // 最下位ビットを1とAND演算(→ 1であれば1を、0であれば0を返す)
		num >>= 1             // 1ビット右にシフト
	}
	return count
}
0