結果

問題 No.3 ビットすごろく
ユーザー maruyuki95maruyuki95
提出日時 2020-05-22 22:47:27
言語 Java21
(openjdk 21)
結果
TLE  
実行時間 -
コード長 1,730 bytes
コンパイル時間 2,251 ms
コンパイル使用メモリ 77,708 KB
実行使用メモリ 54,176 KB
最終ジャッジ日時 2024-04-15 17:54:56
合計ジャッジ時間 9,104 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int arg = sc.nextInt();
		int ret = new Main().execute(arg);
		System.out.println(ret);
	}

	private int execute(int goal) {
		List<Integer> routes = new ArrayList<Integer>();
		searchRoute(1, goal, routes);
		if (moveMin == null) {
			return -1;
		}
		return moveMin.intValue();
	}

	private Integer moveMin = null;
	private void searchRoute(int location, int goal, List<Integer> routes) {
		List<Integer> afterRoutes = new ArrayList<Integer>(routes);
 		afterRoutes.add(location);

		if (location == goal) {
			if (moveMin == null || afterRoutes.size() < moveMin.intValue()) {
				moveMin = afterRoutes.size();
			}
			return ;
		}

		int binaryTotal = calcurateBinaryTotal(location);

		int locationForward = location + binaryTotal;
		if (canMove(goal, afterRoutes, locationForward)) {
			searchRoute(locationForward, goal, afterRoutes);
		}

		int locationBackward = location - binaryTotal;
		if (canMove(goal, afterRoutes, locationBackward)){
			searchRoute(locationBackward, goal, afterRoutes);
		}
	}

	private boolean canMove(int goal, List<Integer> routes, int location) {
		return 1 <= location && location <= goal && !routes.contains(location);
	}


	/**
	 * 10進数の数値を2進数で表現した時の1のビット数を返す
	 * @param decimalNumber	10進数
	 * @return	2進数で表現した時の1のビット数
	 */
	private int calcurateBinaryTotal(int decimalNumber) {
		int ret = 0;
		int quotient = decimalNumber;
		do {
			ret += quotient % 2;
			quotient = quotient / 2;
		} while (quotient > 0);

		return ret;
	}

}
0