結果

問題 No.626 Randomized 01 Knapsack
ユーザー merom686merom686
提出日時 2017-12-20 17:51:12
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 4 ms / 2,000 ms
コード長 1,170 bytes
コンパイル時間 895 ms
コンパイル使用メモリ 80,748 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-06-26 03:30:15
合計ジャッジ時間 1,812 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 25
権限があれば一括ダウンロードができます

ソースコード

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