結果

問題 No.626 Randomized 01 Knapsack
ユーザー merom686merom686
提出日時 2017-12-20 17:51:12
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 4 ms / 2,000 ms
コード長 1,170 bytes
コンパイル時間 862 ms
コンパイル使用メモリ 80,524 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-09-08 10:09:05
合計ジャッジ時間 1,811 ms
ジャッジサーバーID
(参考情報)
judge13 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;

struct Item {
    bool operator<(const Item& o) const {
        return (double)v * o.w < (double)o.v * w;
    }
    int64_t v, w;
};

vector<Item> o;
int64_t v_max;

void dfs(int d, int64_t v, int64_t w) {
    if (d < 0 || w == 0) {
        v_max = max(v_max, v);
        return;
    }

    int d1 = d;
    int64_t v1 = v, w1 = w;
    for (; d1 >= 0; d1--) {
        if (w1 - o[d1].w < 0) break;
        v1 += o[d1].v;
        w1 -= o[d1].w;
    }

    if (d1 < 0 || w1 == 0) {
        v_max = max(v_max, v1);
        return;
    }

    if (v_max - v1 >= (double)o[d1].v / o[d1].w * w1) return;

    int64_t w2 = w - o[d].w;
    if (w2 >= 0) dfs(d - 1, v + o[d].v, w2);
    dfs(d - 1, v, w);
}

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

    int n;
    cin >> n;

    int64_t W;
    cin >> W;

    o.resize(n);
    for (int i = 0; i < n; i++) {
        cin >> o[i].v >> o[i].w;
    }

    sort(o.begin(), o.end());

    v_max = 0;
    dfs(n - 1, 0, W);

    cout << v_max << endl;

    return 0;
}
0