結果

問題 No.458 異なる素数の和
ユーザー 赤信号赤信号
提出日時 2024-03-17 20:43:35
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 85 ms / 2,000 ms
コード長 1,298 bytes
コンパイル時間 3,395 ms
コンパイル使用メモリ 184,608 KB
実行使用メモリ 5,248 KB
最終ジャッジ日時 2024-09-30 04:45:21
合計ジャッジ時間 4,802 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 28
権限があれば一括ダウンロードができます

ソースコード

diff #

#if __has_include(<atcoder/all>)
#include <atcoder/all>
#endif

#ifdef LOCAL
#include "algo/debug.h"
#else
#define _debug(...) 42
#endif

#include <iostream>
#include <cstddef>
#include <vector>
#include <optional>
#include <algorithm>

std::vector<std::size_t> enumerate_primes(std::size_t x) {
    std::vector<bool> bit_primes(x + 1, true);
    bit_primes[0] = bit_primes[1] = false;

    for (std::size_t i = 2; i * i <= x; ++i) if (bit_primes[i]) for (std::size_t j = 2; i * j <= x; ++j) bit_primes[i * j] = false;

    std::vector<std::size_t> ret;
    for (std::size_t i = 0; i <= x; ++i) if (bit_primes[i]) ret.push_back(i);

    return ret;
}

int main() {
	std::cin.tie(nullptr);
	std::ios::sync_with_stdio(false);

    std::size_t n;
    std::cin >> n;

    std::vector<std::size_t> primes = enumerate_primes(n);
    std::size_t m = primes.size();

    std::vector<std::optional<std::size_t>> dp(n + 1, std::nullopt);
    dp[0] = 0;

    for (std::size_t i = 0; i < m; ++i) {
        for (std::size_t j = n; j-- >= 1;) {
            if (!dp[j].has_value()) continue;

            if (j + primes[i] <= n) dp[j + primes[i]] = std::max(dp[j + primes[i]].value_or(0), dp[j].value() + 1);
        }
    }

    std::cout << (dp[n].has_value() ? (int)dp[n].value() : -1) << '\n';
    return 0;
}
0