結果

問題 No.626 Randomized 01 Knapsack
ユーザー 0w10w1
提出日時 2017-12-26 14:59:43
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
TLE  
実行時間 -
コード長 1,735 bytes
コンパイル時間 2,195 ms
コンパイル使用メモリ 208,760 KB
実行使用メモリ 7,684 KB
最終ジャッジ日時 2023-08-22 21:47:55
合計ジャッジ時間 5,803 ms
ジャッジサーバーID
(参考情報)
judge14 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

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 + 1.0 * v[j] *w[j] * (max_w - lr_w);

        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