結果

問題 No.626 Randomized 01 Knapsack
ユーザー pekempeypekempey
提出日時 2017-12-15 21:40:32
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
TLE  
実行時間 -
コード長 1,195 bytes
コンパイル時間 651 ms
コンパイル使用メモリ 73,240 KB
実行使用メモリ 8,756 KB
最終ジャッジ日時 2023-08-22 01:31:56
合計ジャッジ時間 4,821 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
8,756 KB
testcase_01 AC 2 ms
4,376 KB
testcase_02 AC 1 ms
4,380 KB
testcase_03 AC 2 ms
4,380 KB
testcase_04 AC 1 ms
4,376 KB
testcase_05 AC 2 ms
4,376 KB
testcase_06 AC 2 ms
4,376 KB
testcase_07 AC 4 ms
4,376 KB
testcase_08 AC 88 ms
4,376 KB
testcase_09 AC 5 ms
4,380 KB
testcase_10 AC 4 ms
4,380 KB
testcase_11 TLE -
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 <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 ans;

// ***************************........
// [--------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 + (double)V[ p[i] ] / W[ p[i] ] * (C - w) < 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 (double)V[i] / W[i] > (double)V[j] / W[j]; 
  });

  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 + (double)V[ p[i + 1] ] / W[ p[i + 1] ] * (C - w) < ans - 1e-8) break;
    dfs(w, v, i + 1);
  }

  cout << ans << endl;
}
0