結果

問題 No.3 ビットすごろく
ユーザー shinwisteria
提出日時 2017-04-02 11:37:16
言語 Java
(openjdk 23)
結果
AC  
実行時間 148 ms / 5,000 ms
コード長 763 bytes
コンパイル時間 3,680 ms
コンパイル使用メモリ 78,408 KB
実行使用メモリ 54,284 KB
最終ジャッジ日時 2024-07-01 08:38:22
合計ジャッジ時間 9,557 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 33
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.ArrayDeque;
import java.util.Scanner;

public class Bitsugoroku {

	public static void main(String[] args) {
		Scanner s =new Scanner(System.in);
		int N = s.nextInt();
		s.close();
		int[] way = new int[N+1];
		way[1] = 1;
		ArrayDeque<Integer> queue = new ArrayDeque<>();
		queue.offer(1);
		while(queue.size() != 0){
			int p = queue.poll();
			if(p == N){
				break;
			}
			int b = Integer.bitCount(p);
			if(p+b <= N){
				if(way[p+b] == 0||way[p+b] > way[p]+1){
					queue.offer(p+b);
					way[p+b] = way[p] + 1;
				}
			}
			if(p-b > 0&&( way[p-b] == 0 || way[p-b] > way[p] + 1)){
				queue.offer(p-b);
				way[p-b] = way[p] + 1;
			}
		}
		if(way[N] == 0){
			System.out.println("-1");
		}else{
			System.out.println(way[N]);
		}
	}

}
0