結果

問題 No.3 ビットすごろく
ユーザー Takuya ItoTakuya Ito
提出日時 2023-12-15 09:25:53
言語 Go
(1.22.1)
結果
WA  
実行時間 -
コード長 2,094 bytes
コンパイル時間 13,745 ms
コンパイル使用メモリ 223,352 KB
実行使用メモリ 6,676 KB
最終ジャッジ日時 2023-12-15 09:26:08
合計ジャッジ時間 13,056 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
6,676 KB
testcase_01 AC 1 ms
6,676 KB
testcase_02 WA -
testcase_03 WA -
testcase_04 AC 2 ms
6,676 KB
testcase_05 WA -
testcase_06 WA -
testcase_07 AC 1 ms
6,676 KB
testcase_08 AC 1 ms
6,676 KB
testcase_09 AC 1 ms
6,676 KB
testcase_10 AC 2 ms
6,676 KB
testcase_11 AC 2 ms
6,676 KB
testcase_12 WA -
testcase_13 WA -
testcase_14 WA -
testcase_15 WA -
testcase_16 AC 1 ms
6,676 KB
testcase_17 AC 1 ms
6,676 KB
testcase_18 AC 1 ms
6,676 KB
testcase_19 AC 2 ms
6,676 KB
testcase_20 AC 1 ms
6,676 KB
testcase_21 AC 2 ms
6,676 KB
testcase_22 WA -
testcase_23 WA -
testcase_24 AC 2 ms
6,676 KB
testcase_25 AC 1 ms
6,676 KB
testcase_26 WA -
testcase_27 AC 2 ms
6,676 KB
testcase_28 AC 2 ms
6,676 KB
testcase_29 AC 2 ms
6,676 KB
testcase_30 AC 2 ms
6,676 KB
testcase_31 AC 2 ms
6,676 KB
testcase_32 AC 1 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 // 開始のマスへも移動にカウントすることから

	// ゴールが1なら、それがゴール(開始のマスがすでにゴールになっている場合)
	if n == 1 {
		fmt.Println(0)
		return
	}

	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
		}
	}

	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