結果

問題 No.50 おもちゃ箱
ユーザー Pachicobue
提出日時 2017-07-14 15:17:52
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 11 ms / 5,000 ms
コード長 2,115 bytes
コンパイル時間 1,712 ms
コンパイル使用メモリ 176,332 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-06-25 22:04:53
合計ジャッジ時間 2,914 ms
ジャッジサーバーID
(参考情報)
judge3 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 38
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

#define show(x) cout << #x << " = " << x << endl

using namespace std;
using ll = long long;
using pii = pair<int, int>;
using vi = vector<int>;

template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v)
{
    os << "sz=" << v.size() << "\n[";
    for (const auto& p : v) {
        os << p << ",";
    }
    os << "]\n";
    return os;
}

template <typename S, typename T>
ostream& operator<<(ostream& os, const pair<S, T>& p)
{
    os << "(" << p.first << "," << p.second
       << ")";
    return os;
}


constexpr ll MOD = 1e9 + 7;

template <typename T>
constexpr T INF = numeric_limits<T>::max() / 100;

int main()
{
    int N;
    cin >> N;
    vector<int> A(N);
    for (ll i = 0; i < N; i++) {
        cin >> A[i];
    }
    sort(A.begin(), A.end());
    int M;
    cin >> M;
    vector<int> B(M);
    for (ll i = 0; i < M; i++) {
        cin >> B[i];
    }
    sort(B.begin(), B.end(), greater<int>());


    const int maximum = 1 << N;
    vector<int> sum(maximum);
    sum[0] = 0;
    for (int i = 1; i < maximum; i++) {
        const int ind = __builtin_ctz(i);
        sum[i] = A[ind] + sum[i - (1 << ind)];
    }


    vector<vector<int>> dp(M + 1, vector<int>(maximum, INF<int>));  // i番目の箱まで使っておもちゃの組み合わせjを収納するときの必要箱数
    dp[0][0] = 0;
    for (int m = 0; m < M; m++) {
        for (int c = 0; c < maximum; c++) {
            if (dp[m][c] != INF<int>) {
                // m+1番目の箱に何も入れない
                dp[m + 1][c] = min(dp[m + 1][c], dp[m][c]);

                // m+1番目の箱に入れる
                for (int addc = 1; addc < maximum; addc++) {  // m+1番目の箱にどれを入れるか
                    if ((c & addc) == 0 and sum[addc] <= B[m]) {
                        dp[m + 1][c | addc] = min(dp[m + 1][c | addc], dp[m][c] + 1);
                    }
                }
            }
        }
    }
    if (dp[M][maximum - 1] != INF<int>) {
        cout << dp[M][maximum - 1] << endl;
    } else {
        cout << -1 << endl;
    }

    return 0;
}
0