結果

問題 No.626 Randomized 01 Knapsack
ユーザー zimphazimpha
提出日時 2017-12-16 21:27:05
言語 C++17
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 4 ms / 2,000 ms
コード長 1,177 bytes
コンパイル時間 352 ms
コンパイル使用メモリ 48,864 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-08 10:06:40
合計ジャッジ時間 1,415 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ(β)

テストケース

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

ソースコード

diff #

#include <cstdio>
#include <utility>
#include <algorithm>

using int64 = long long;
using int128 = __int128;
using pii = std::pair<int64, int64>;

const int N = 5000 + 10;

pii items[N];
int64 cap, best;
int n;

void dfs(int d, int64 value, int64 weight) {
  if (cap < weight) return;
  best = std::max(best, value);
  if (d == n) return;
  int64 t_value = value, t_weight = cap - weight;
  int t_d;
  for (t_d = d; t_d < n && items[t_d].second <= t_weight; ++t_d) {
    t_value += items[t_d].first;
    t_weight -= items[t_d].second;
  }
  if (t_d == n || t_weight == 0) {
    best = std::max(best, t_value);
    return;
  }
  double t_opt = t_value + (double)items[t_d].first * t_weight / items[t_d].second;
  if (t_opt <= best) return;
  dfs(d + 1, value + items[d].first, weight + items[d].second);
  dfs(d + 1, value, weight);
}

int main() {
  scanf("%d%lld", &n, &cap);
  for (int i = 0; i < n; ++i) {
    scanf("%lld%lld", &items[i].first, &items[i].second);
  }
  std::sort(items, items + n, [](const pii &a, const pii &b) {
      return (int128)a.first * b.second > (int128)b.first * a.second;
  });
  best = 0;
  dfs(0, 0, 0);
  printf("%lld\n", best);
  return 0;
}
0