結果

問題 No.3 ビットすごろく
ユーザー YamaKasaYamaKasa
提出日時 2018-06-08 02:53:45
言語 Java21
(openjdk 21)
結果
AC  
実行時間 172 ms / 5,000 ms
コード長 1,416 bytes
コンパイル時間 2,086 ms
コンパイル使用メモリ 74,952 KB
実行使用メモリ 60,476 KB
最終ジャッジ日時 2023-09-14 01:02:54
合計ジャッジ時間 8,545 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 124 ms
55,556 KB
testcase_01 AC 129 ms
55,540 KB
testcase_02 AC 127 ms
55,724 KB
testcase_03 AC 160 ms
55,792 KB
testcase_04 AC 137 ms
55,584 KB
testcase_05 AC 163 ms
56,288 KB
testcase_06 AC 150 ms
58,368 KB
testcase_07 AC 137 ms
55,724 KB
testcase_08 AC 163 ms
57,928 KB
testcase_09 AC 160 ms
58,716 KB
testcase_10 AC 161 ms
58,220 KB
testcase_11 AC 160 ms
58,048 KB
testcase_12 AC 163 ms
58,048 KB
testcase_13 AC 138 ms
55,744 KB
testcase_14 AC 166 ms
60,476 KB
testcase_15 AC 165 ms
58,484 KB
testcase_16 AC 163 ms
58,228 KB
testcase_17 AC 162 ms
58,728 KB
testcase_18 AC 139 ms
55,420 KB
testcase_19 AC 164 ms
58,068 KB
testcase_20 AC 130 ms
55,444 KB
testcase_21 AC 125 ms
55,580 KB
testcase_22 AC 171 ms
58,844 KB
testcase_23 AC 164 ms
58,480 KB
testcase_24 AC 161 ms
58,212 KB
testcase_25 AC 172 ms
58,276 KB
testcase_26 AC 125 ms
55,544 KB
testcase_27 AC 139 ms
55,604 KB
testcase_28 AC 161 ms
58,160 KB
testcase_29 AC 156 ms
57,992 KB
testcase_30 AC 128 ms
55,488 KB
testcase_31 AC 127 ms
55,580 KB
testcase_32 AC 163 ms
57,856 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int N = scan.nextInt();
		scan.close();

		// マスの状態 0: 訪れていない 1: 訪れた
		int []color = new int[N];
		Arrays.fill(color, 0);
		color[0] = 1;

		// 次に訪問すべきマス
		Queue<Integer> queue = new ArrayDeque<Integer>();
		queue.add(1);

		// 1からの距離
		int []d = new int[N];
		Arrays.fill(d, 0);
		d[0] = 1;
		while(queue.size() > 0){
			// 訪問しているマス
			int k = queue.poll();
			// 移動可能な距離
			int t = bitNum(k);
			// 移動するマス
			int a1 = k + t;
			int a2 = k - t;
			//System.out.println(a1 + " " + a2);
			if(a1 <= N) {
				if(color[a1 - 1] == 0){
					color[a1 - 1] = 1;
					d[a1 - 1] = d[k - 1] + 1;
					queue.add(a1);
				}
			}
			if(a2 >= 2) {
				if(color[a2 - 1] == 0) {
					color[a2 - 1] = 1;
					d[a2 - 1] = d[k - 1] + 1;
					queue.add(a2);
				}
			}
			if(color[N - 1] == 1) {
				System.out.println(d[N - 1]);
				System.exit(0);
			}

		}
		System.out.println(-1);

	}
	public static int bitNum(int a) {
		int cnt = 0;
		String binary = Integer.toBinaryString(a);
		int l = binary.length();
		for(int j = 0; j < l; j++) {
			if(binary.substring(j, j+1).equals("1")) {
				cnt ++;
			}
		}
		return cnt;
	}
}
0