結果

問題 No.2869 yuusaan's Knapsacks
ユーザー vjudge1
提出日時 2024-09-21 23:48:03
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 1,906 ms / 4,500 ms
コード長 1,259 bytes
コンパイル時間 4,936 ms
コンパイル使用メモリ 275,888 KB
実行使用メモリ 17,772 KB
最終ジャッジ日時 2024-09-21 23:48:22
合計ジャッジ時間 18,586 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 27
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;
using ll = long long;

const int N = 20;

int n, m, a[N], b[N], c[N], pre[N][1 << 16];
ll dp[N][1 << 16], ans;

void dfs(int i, int t, int x, int y, ll sum, ll s) {
    if (sum > a[x]) return ;
    if (i == m) {
        ll k = dp[x - 1][(y ^ t) & y] + s;
        if (k > dp[x][y]) {
            dp[x][y] = k, pre[x][y] = t;
        }
        return ;
    }
    dfs(i + 1, t, x, y, sum, s);
    if (y & (1 << i)) {
        dfs(i + 1, t | (1 << i), x, y, sum + c[i + 1], s + b[i + 1]);
    }
}

void print(int x, int y) {
    if (!x) return ;
    print(x - 1, (y ^ pre[x][y]) & y);
    vector<int> p;
    for (int i = 0; i < m; i++) {
        if (pre[x][y] & (1 << i)) p.push_back(i + 1);
    }
    cout << p.size() << ' ';
    for (int x : p) cout << x << ' ';
    cout << '\n';
}

int main() {
    ios::sync_with_stdio(0), cin.tie(0);
    cin >> n >> m;
    for (int i = 1; i <= n; i++) cin >> a[i];
    for (int i = 1; i <= m; i++) cin >> b[i] >> c[i];
    for (int i = 1; i <= n; i++) {
        for (int j = 0; j < (1 << m); j++) {
            dfs(0, 0, i, j, 0, 0);
            if (i == n && dp[i][j] > dp[i][ans]) ans = j;
        }
    }
    cout << dp[n][ans] << '\n', print(n, ans);
    return 0;
}
//////
0