結果

問題 No.626 Randomized 01 Knapsack
ユーザー kimiyukikimiyuki
提出日時 2017-12-18 09:32:46
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 7 ms / 2,000 ms
コード長 1,687 bytes
コンパイル時間 3,897 ms
コンパイル使用メモリ 206,844 KB
実行使用メモリ 4,500 KB
最終ジャッジ日時 2023-09-08 10:08:05
合計ジャッジ時間 3,502 ms
ジャッジサーバーID
(参考情報)
judge11 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,380 KB
testcase_01 AC 2 ms
4,380 KB
testcase_02 AC 1 ms
4,380 KB
testcase_03 AC 2 ms
4,380 KB
testcase_04 AC 1 ms
4,380 KB
testcase_05 AC 2 ms
4,376 KB
testcase_06 AC 2 ms
4,380 KB
testcase_07 AC 3 ms
4,380 KB
testcase_08 AC 2 ms
4,376 KB
testcase_09 AC 3 ms
4,380 KB
testcase_10 AC 4 ms
4,376 KB
testcase_11 AC 7 ms
4,380 KB
testcase_12 AC 7 ms
4,380 KB
testcase_13 AC 7 ms
4,380 KB
testcase_14 AC 6 ms
4,380 KB
testcase_15 AC 7 ms
4,376 KB
testcase_16 AC 7 ms
4,376 KB
testcase_17 AC 7 ms
4,380 KB
testcase_18 AC 6 ms
4,380 KB
testcase_19 AC 7 ms
4,500 KB
testcase_20 AC 7 ms
4,376 KB
testcase_21 AC 7 ms
4,380 KB
testcase_22 AC 7 ms
4,376 KB
testcase_23 AC 7 ms
4,380 KB
testcase_24 AC 6 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
#define REP(i, n) for (int i = 0; (i) < int(n); ++ (i))
#define ALL(x) begin(x), end(x)
using ll = long long;
using namespace std;
template <class T> inline void chmax(T & a, T const & b) { a = max(a, b); }

ll knapsack_problem_branch_and_bound(int n, ll max_w, vector<ll> const & a_v, vector<ll> const & a_w) {
    vector<ll> v(n), w(n); {
        vector<int> xs(n);
        iota(ALL(xs), 0);
        sort(ALL(xs), [&](int i, int j) {
            return a_v[i] *(double) a_w[j] > a_v[j] *(double) a_w[i];
        });
        REP (i, n) {
            v[i] = a_v[xs[i]];
            w[i] = a_w[xs[i]];
        }
    }
    ll ans = 0;
    function<void (int, ll, ll)> go = [&](int i, ll cur_v, ll cur_w) {
        if (max_w < cur_w) return; // not executable
        if (i == n) {
            chmax(ans, cur_v);
            return; // terminate
        }
        ll lr_v = cur_v; // linear relaxation
        ll lr_w = cur_w;
        int j = i;;
        for (; j < n and lr_w + w[j] <= max_w; ++ j) { // greedy
            lr_w += w[j];
            lr_v += v[j];
        }
        if (lr_w == max_w or j == n) {
            chmax(ans, lr_v);
            return; // accept greedy
        }
        double lr_ans = lr_v + v[j] * ((max_w - lr_w) /(double) w[j]);
        if (lr_ans <= ans) return; // bound
        go(i + 1, cur_v + v[i], cur_w + w[i]);
        go(i + 1, cur_v,        cur_w       );
    };
    go(0, 0, 0);
    return ans;
}

int main() {
    int n; ll max_w; cin >> n >> max_w;
    vector<ll> v(n), w(n); REP (i, n) cin >> v[i] >> w[i];
    ll result = knapsack_problem_branch_and_bound(n, max_w, v, w);
    cout << result << endl;
    return 0;
}
0