結果

問題 No.3 ビットすごろく
ユーザー mosmos_21mosmos_21
提出日時 2017-06-17 11:02:59
言語 Java
(openjdk 23)
結果
WA  
実行時間 -
コード長 861 bytes
コンパイル時間 2,883 ms
コンパイル使用メモリ 79,404 KB
実行使用メモリ 54,280 KB
最終ジャッジ日時 2024-10-01 09:29:11
合計ジャッジ時間 7,505 ms
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 32 WA * 1
権限があれば一括ダウンロードができます

ソースコード

diff #

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

public class Main {
	static Scanner in = new Scanner(System.in);

	public static void main(String[] args) {
		int n = in.nextInt();
		int[] d = new int[n + 1];
		Arrays.fill(d, Integer.MAX_VALUE);
		d[1] = 1;
		Deque<Integer> q = new ArrayDeque<>();
		q.add(1);
		while (q.size() > 0) {
			int a = q.poll(), b = bit(a);
			if(a + b == n){
				System.out.println(d[a] + 1);
				return;
			}
			if (0 < a - b && d[a - b] == Integer.MAX_VALUE) {
				d[a - b] = d[a] + 1;
				q.add(a - b);
			}
			if (a + b <= n && d[a + b] == Integer.MAX_VALUE) {
				d[a + b] = d[a] + 1;
				q.add(a + b);
			}
		}
		System.out.println(-1);
	}

	public static int bit(int n) {
		int s = 0;
		while (n > 0) {
			if (n % 2 == 1) {
				s++;
			}
			n /= 2;
		}
		return s;
	}
}
0