結果

問題 No.3 ビットすごろく
ユーザー atkrymatkrym
提出日時 2016-11-07 15:01:06
言語 Java21
(openjdk 21)
結果
AC  
実行時間 143 ms / 5,000 ms
コード長 1,453 bytes
コンパイル時間 2,118 ms
コンパイル使用メモリ 74,724 KB
実行使用メモリ 56,476 KB
最終ジャッジ日時 2023-09-14 00:11:58
合計ジャッジ時間 8,005 ms
ジャッジサーバーID
(参考情報)
judge14 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 125 ms
55,952 KB
testcase_01 AC 126 ms
55,936 KB
testcase_02 AC 126 ms
55,996 KB
testcase_03 AC 136 ms
55,488 KB
testcase_04 AC 130 ms
55,960 KB
testcase_05 AC 137 ms
55,860 KB
testcase_06 AC 137 ms
55,684 KB
testcase_07 AC 132 ms
55,792 KB
testcase_08 AC 139 ms
55,800 KB
testcase_09 AC 140 ms
55,904 KB
testcase_10 AC 142 ms
55,508 KB
testcase_11 AC 137 ms
55,852 KB
testcase_12 AC 138 ms
55,804 KB
testcase_13 AC 131 ms
56,000 KB
testcase_14 AC 143 ms
56,108 KB
testcase_15 AC 142 ms
55,824 KB
testcase_16 AC 143 ms
56,092 KB
testcase_17 AC 143 ms
56,356 KB
testcase_18 AC 131 ms
55,800 KB
testcase_19 AC 142 ms
55,544 KB
testcase_20 AC 131 ms
55,972 KB
testcase_21 AC 127 ms
55,540 KB
testcase_22 AC 141 ms
56,060 KB
testcase_23 AC 142 ms
55,636 KB
testcase_24 AC 142 ms
56,112 KB
testcase_25 AC 141 ms
55,804 KB
testcase_26 AC 127 ms
55,684 KB
testcase_27 AC 131 ms
55,524 KB
testcase_28 AC 143 ms
55,612 KB
testcase_29 AC 138 ms
53,832 KB
testcase_30 AC 127 ms
56,476 KB
testcase_31 AC 127 ms
56,180 KB
testcase_32 AC 139 ms
56,316 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;

public class Main {
    private static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) throws Exception {
        int n = sc.nextInt();
        int[] dp = new int[n+1];
        Deque<Pair> que = new ArrayDeque<>();
        que.addLast(new Pair(1, 1));
        dp[1] = 1;
        while (true) {
            if (que.isEmpty()) break;
            Pair p = que.pollFirst();
            int m = count(p.val);
            int nn = p.val-m;
            int np = p.val+m;
            int nc = p.cnt+1;
            if (nn>0) {
                if (dp[nn]==0) {
                    dp[nn] = nc;
                    que.addLast(new Pair(nn,nc));
                }
            }
            if (np<=n) {
                if (dp[np]==0) {
                    dp[np] = nc;
                    que.addLast(new Pair(np,nc));
                }
            }
        }
        
        if (dp[n]==0) {
            System.out.println(-1);
        } else {
            System.out.println(dp[n]);
        }
    }
    
    private static int count(int val) {
        String s = Integer.toBinaryString(val);
        int ret = 0;
        for (int i = 0;i < s.length();i++) {
            if (s.charAt(i)=='1') ret++;
        }
        return ret;
    }

    static class Pair {
        public int val;
        public int cnt;
        public Pair(int a, int b) {
            val = a;
            cnt = b;
        }
    }
}
    
0