結果

問題 No.3 ビットすごろく
ユーザー yuki2006
提出日時 2014-09-30 02:11:29
言語 Java
(openjdk 23)
結果
WA  
実行時間 -
コード長 1,440 bytes
コンパイル時間 2,314 ms
コンパイル使用メモリ 78,596 KB
実行使用メモリ 56,252 KB
最終ジャッジ日時 2024-12-30 06:41:50
合計ジャッジ時間 8,356 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 18 WA * 15
権限があれば一括ダウンロードができます

ソースコード

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));

    }

    public static class Tuple {
        public int a;
        public int b;

        Tuple(int a, int b) {
            this.a = a;
            this.b = b;
        }

    }

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

            Tuple v = queue.pop();
            if (v.a == n) {
                return v.b;
            }


            check[v.a] = true;

            int bitCount = getBitCount(v.a);

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


            if (a > 0) {
                if (!check[a]) {
                    queue.push(new Tuple(a, v.b + 1));
                }
            }
            if (b <= n) {
                if (!check[b]) {
                    queue.push(new Tuple(b, v.b + 1));
                }
            }
        }
        return -1;
    }


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

}
0