結果

問題 No.626 Randomized 01 Knapsack
ユーザー pekempeypekempey
提出日時 2017-12-15 22:10:21
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 8 ms / 2,000 ms
コード長 1,699 bytes
コンパイル時間 711 ms
コンパイル使用メモリ 73,284 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-09-08 10:06:38
合計ジャッジ時間 1,794 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ(β)

テストケース

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

ソースコード

diff #

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

const int N = 5000;
int n;
long long C;
long long V[N];
long long W[N];
int p[N];
long long sumV[N + 1];
long long sumW[N + 1];

long long ans;

long double estimate(long long A, int k) {
  int ok = k;
  int ng = n + 1;
  while (ng - ok > 1) {
    int mid = (ok + ng) / 2;
    if (sumW[mid] - sumW[k] <= A) {
      ok = mid;
    } else {
      ng = mid;
    }
  }
  long double ret = sumV[ok] - sumV[k];
  A -= sumW[ok] - sumW[k];
  if (ok < n) {
    ret += A * (long double)V[ p[ok] ] / W[ p[ok] ];
  }

  return ret;
}

// ***************************........
// [--------greedy-----------]
//
// **********************.*...*.**....
// [--------core--------]
void dfs(long long w, long long v, int k) {
  if (w > C) return;
  ans = max(ans, v);

  for (int i = k; i < n; i++) {
    // You can estimate the upper bound by Rational Knapsack problem.
    if (v + estimate(C - w, i) < ans - 1e-8) break;
    dfs(w + W[ p[i] ], v + V[ p[i] ], i + 1);
  }
}

int main() {
  cin >> n >> C;

  for (int i = 0; i < n; i++) {
    cin >> V[i] >> W[i];
    p[i] = i;
  }

  sort(p, p + n, [&](int i, int j) {
   return (long double)V[i] / W[i] > (long double)V[j] / W[j]; 
  });

  for (int i = 0; i < n; i++) {
    sumV[i + 1] = sumV[i] + V[ p[i] ];
    sumW[i + 1] = sumW[i] + W[ p[i] ];
  }

  long long v = 0;
  long long w = 0;
  int k = 0;
  while (k < n) {
    v += V[ p[k] ];
    w += W[ p[k] ];
    k++;
    if (w > C) break;
  }

  for (int i = k - 1; i >= 0; i--) {
    w -= W[ p[i] ];
    v -= V[ p[i] ];
    if (v + estimate(C - w, i + 1) < ans - 1e-8) continue;
    dfs(w, v, i + 1);
  }

  cout << ans << endl;
}
0