結果

問題 No.3 ビットすごろく
ユーザー aimBULLaimBULL
提出日時 2016-06-02 00:53:56
言語 Java21
(openjdk 21)
結果
AC  
実行時間 136 ms / 5,000 ms
コード長 1,306 bytes
コンパイル時間 2,167 ms
コンパイル使用メモリ 77,516 KB
実行使用メモリ 57,848 KB
最終ジャッジ日時 2023-09-13 23:59:19
合計ジャッジ時間 7,991 ms
ジャッジサーバーID
(参考情報)
judge14 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 131 ms
55,748 KB
testcase_01 AC 126 ms
56,024 KB
testcase_02 AC 126 ms
55,844 KB
testcase_03 AC 130 ms
55,976 KB
testcase_04 AC 128 ms
55,896 KB
testcase_05 AC 131 ms
55,792 KB
testcase_06 AC 130 ms
55,900 KB
testcase_07 AC 132 ms
55,752 KB
testcase_08 AC 132 ms
55,720 KB
testcase_09 AC 134 ms
55,748 KB
testcase_10 AC 136 ms
56,040 KB
testcase_11 AC 131 ms
55,744 KB
testcase_12 AC 133 ms
55,704 KB
testcase_13 AC 134 ms
56,192 KB
testcase_14 AC 133 ms
56,184 KB
testcase_15 AC 132 ms
55,840 KB
testcase_16 AC 136 ms
56,208 KB
testcase_17 AC 134 ms
57,848 KB
testcase_18 AC 135 ms
55,724 KB
testcase_19 AC 132 ms
56,256 KB
testcase_20 AC 129 ms
55,460 KB
testcase_21 AC 128 ms
55,464 KB
testcase_22 AC 132 ms
55,816 KB
testcase_23 AC 134 ms
55,896 KB
testcase_24 AC 134 ms
55,876 KB
testcase_25 AC 134 ms
55,952 KB
testcase_26 AC 127 ms
55,764 KB
testcase_27 AC 131 ms
55,876 KB
testcase_28 AC 132 ms
55,768 KB
testcase_29 AC 135 ms
55,852 KB
testcase_30 AC 128 ms
55,992 KB
testcase_31 AC 128 ms
55,728 KB
testcase_32 AC 133 ms
57,576 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		sc.close();

		int[] memo = create(n);
		calc(1, memo);

		System.out.println(memo[n] == Integer.MAX_VALUE ? -1 : memo[n]);
	}

	// データの格納領域を作成する
	public static int[] create(int n){
		int[] memo = new int[n+1];
		memo[0] = Integer.MAX_VALUE;
		memo[1] = 1;
		for(int i = 2; i < memo.length; i++){
			memo[i] = Integer.MAX_VALUE;
		}
		return memo;
	}

	// 移動距離計算する
	// 移動可能なマスの範囲内で移動距離を短縮できる間、再帰的に処理する
	public static void calc(int pos, int[] memo){
		int cnt = Integer.bitCount(pos);

		// 移動した場合の移動距離を計算しておく
		int cost = memo[pos] + 1;

		// 前進
		{
			int nextPos = pos + cnt;
			// 移動数が小さくなるなら、結果を記録して次のマスへ
			if(nextPos < memo.length && cost < memo[nextPos]){
				memo[nextPos] = cost;
				calc(nextPos, memo);
			}
		}

		// 後退
		{
			int prevPos = pos - cnt;
			// 移動数が小さくなるなら、結果を記録して次のマスへ
			if(prevPos > 0 && cost < memo[prevPos]){
				memo[prevPos] = cost;
				calc(prevPos, memo);
			}
		}
	}

}
0