結果

問題 No.626 Randomized 01 Knapsack
ユーザー たこしたこし
提出日時 2017-12-18 13:49:08
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 7 ms / 2,000 ms
コード長 1,379 bytes
コンパイル時間 1,224 ms
コンパイル使用メモリ 147,732 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-09-08 10:08:15
合計ジャッジ時間 2,350 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;
using LL = long long int;

const int MAX_N = 50005;

int N;
class Gift{
public:
  LL V, W;
  double value;
  void input()
  {
    cin >> V >> W;
    value = (double)V/(double)W;
  }

  bool operator < (const Gift& p) const {
    return value < p.value;
  }

  bool operator > (const Gift& p) const {
    return value > p.value;
  }
}G[MAX_N];
LL W;

LL ans = 0;
LL solve(int pos = 0, LL tmpV = 0, LL tmpW = 0)
{
  if((double)ans > tmpV + (double)(W-tmpW)*G[pos].value) {
    return tmpV;
  }

  if(pos == N) {
    ans = max(ans, tmpV);
    return tmpV;
  }

  double tV = tmpV;
  int tW = tmpW;
  for(int i = pos; i < N; i++){
    if(tW + G[i].W <= W){
      tW += G[i].W;
      tV += G[i].V;
    }
    else{
      tV += (double)G[i].V/G[i].W * (W - tW);
      break;
    }
  }

  if(tV < ans) {
    return tmpV;
  }

  LL ret = 0;
  if(tmpW + G[pos].W <= W) {
    ret = max(ret, solve(pos+1, tmpV+G[pos].V, tmpW+G[pos].W));
  }
  ret = max(ret, solve(pos+1, tmpV, tmpW));
  ans = max(ret, ans);
  return ret;
}

int main()
{
  cin >> N >> W;
  for(int i = 0; i < N; i++) {
    G[i].input();
  }

  sort(G, G+N, greater<Gift>());

  LL tmpW = 0;
  for(int i = 0; i < N; i++) {
    if(tmpW + G[i].W <= W) {
      tmpW += G[i].W;
      ans += G[i].V;
    }
  }

  cerr << ans << endl;
  solve();
  cout << ans << endl;

  return 0;
}
0