結果

問題 No.458 異なる素数の和
ユーザー htensaihtensai
提出日時 2019-12-12 20:01:13
言語 Java21
(openjdk 21)
結果
AC  
実行時間 546 ms / 2,000 ms
コード長 1,388 bytes
コンパイル時間 3,898 ms
コンパイル使用メモリ 74,312 KB
実行使用メモリ 233,640 KB
最終ジャッジ日時 2023-09-07 20:14:08
合計ジャッジ時間 10,004 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 129 ms
56,116 KB
testcase_01 AC 241 ms
114,548 KB
testcase_02 AC 279 ms
131,304 KB
testcase_03 AC 174 ms
68,064 KB
testcase_04 AC 176 ms
67,756 KB
testcase_05 AC 470 ms
230,468 KB
testcase_06 AC 281 ms
132,144 KB
testcase_07 AC 141 ms
56,156 KB
testcase_08 AC 485 ms
230,648 KB
testcase_09 AC 147 ms
60,768 KB
testcase_10 AC 122 ms
55,576 KB
testcase_11 AC 546 ms
233,640 KB
testcase_12 AC 123 ms
55,700 KB
testcase_13 AC 122 ms
55,680 KB
testcase_14 AC 120 ms
55,732 KB
testcase_15 AC 121 ms
56,156 KB
testcase_16 AC 157 ms
60,584 KB
testcase_17 AC 123 ms
55,856 KB
testcase_18 AC 124 ms
55,652 KB
testcase_19 AC 119 ms
55,956 KB
testcase_20 AC 121 ms
56,036 KB
testcase_21 AC 118 ms
55,760 KB
testcase_22 AC 118 ms
56,368 KB
testcase_23 AC 125 ms
56,032 KB
testcase_24 AC 120 ms
56,056 KB
testcase_25 AC 121 ms
55,952 KB
testcase_26 AC 118 ms
55,540 KB
testcase_27 AC 275 ms
130,940 KB
testcase_28 AC 513 ms
229,064 KB
testcase_29 AC 138 ms
58,536 KB
testcase_30 AC 213 ms
87,796 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;
import java.io.*;

public class Main {
    static int size;
    static int[][] dp;
    static ArrayList<Integer> primes = new ArrayList<>();
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i = 2; i <= n; i++) {
            if (isPrime(i)) {
                primes.add(i);
            }
        }
        size = primes.size();
        dp = new int[size][n + 1];
        int ret = dfw(size - 1, n);
        if (ret <= 0) {
            System.out.println(-1);
        } else {
            System.out.println(ret);
        }
    }
    
    static int dfw(int idx, int num) {
        if (num == 0) {
            return 0;
        }
        if (idx < 0) {
            return Integer.MIN_VALUE;
        }
        if (dp[idx][num] != 0) {
            return dp[idx][num];
        }
        int ret = dfw(idx - 1, num);
        int now = primes.get(idx);
        if (num >= now) {
            ret = Math.max(ret, dfw(idx - 1, num - now) + 1);
        }
        dp[idx][num] = ret;
        return ret;
    }
    
    static boolean isPrime(int num) {
        for (int x : primes) {
            if (Math.sqrt(num) < x) {
                break;
            }
            if (num % x == 0) {
                return false;
            }
        }
        return true;
    }
}
0