結果

問題 No.626 Randomized 01 Knapsack
ユーザー startcppstartcpp
提出日時 2017-12-29 18:33:58
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 7 ms / 2,000 ms
コード長 1,344 bytes
コンパイル時間 678 ms
コンパイル使用メモリ 67,460 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-09-08 10:10:51
合計ジャッジ時間 1,868 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

//v / wが大きいほうから探索 → 分岐限定で枝刈り → 上界の計算を厳しくする(O(n)かけて計算)
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;

struct Baggage {
	double key;
	long long v, w;
	Baggage() {}
	Baggage(long long v, long long w) {
		this->v = v;
		this->w = w;
		key = (double)v / w;
	}
	bool operator>(const Baggage &r) const {
		return key > r.key;
	}
};

int n;
long long w;
Baggage bag[5000];
long long maxSumV;

void maxV(int id, long long remW, long long sumV) {
	if (id == n) {
		maxSumV = max(maxSumV, sumV);
		return;
	}
	
	long double kanwaSumV = 0;
	long double kanwaRemW = remW;
	for (int i = id; i < n; i++) {
		if (kanwaRemW >= bag[i].w) {
			kanwaRemW -= bag[i].w;
			kanwaSumV += bag[i].v;
		}
		else {
			kanwaSumV += bag[i].v * (kanwaRemW / bag[i].w);
			break;
		}
	}
	long long kanwaAns = kanwaSumV + sumV;
	if (kanwaAns <= maxSumV) { return; }
	
	if (remW >= bag[id].w) {
		maxV(id + 1, remW - bag[id].w, sumV + bag[id].v);
	}
	maxV(id + 1, remW, sumV);
}

int main() {
	int i;
	
	cin >> n >> w;
	
	long long sumW = 0;
	for (i = 0; i < n; i++) {
		long long v, w;
		cin >> v >> w;
		bag[i] = Baggage(v, w);
		sumW += w;
	}
	w = min(w, sumW);
	sort(bag, bag + n, greater<Baggage>());
	maxV(0, w, 0);
	cout << maxSumV << endl;
	return 0;
}
0