結果

問題 No.3 ビットすごろく
ユーザー yuki2006
提出日時 2014-09-30 02:08:53
言語 Java
(openjdk 23)
結果
AC  
実行時間 2,261 ms / 5,000 ms
コード長 1,502 bytes
コンパイル時間 2,470 ms
コンパイル使用メモリ 78,088 KB
実行使用メモリ 101,472 KB
最終ジャッジ日時 2024-07-01 07:04:41
合計ジャッジ時間 23,622 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 33
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        int N = scanner.nextInt();
        boolean[] check = new boolean[N + 1];

        System.out.println(bfs(N, check));

    }


    private static int bfs(int n, boolean[] check) {
        LinkedList<Integer> queue = new LinkedList<Integer>();
        LinkedList<Integer> nextQueue = new LinkedList<Integer>();
        queue.add(1);
        for (int turn = 1; queue.size() > 0; turn++) {
            while (queue.size() > 0) {

                int v = queue.pop();
                if (v == n) {
                    return turn;
                }


                check[v] = true;

                int bitCount = getBitCount(v);

                int a = v - bitCount;
                int b = v + bitCount;



                if (a > 0) {
                    if (!check[a]) {
                        nextQueue.push(a);
                    }
                }
                if (b <= n) {
                    if (!check[b]) {

                        nextQueue.push(b);
                    }
                }
            }
            queue.addAll(nextQueue);
            nextQueue.clear();
        }
        return -1;
    }


    static int getBitCount(int n) {
        int count;
        for (count = 0; n > 0; count++) {
            n = n & (n - 1);
        }
        return count;
    }

}
0