結果

問題 No.626 Randomized 01 Knapsack
ユーザー startcppstartcpp
提出日時 2017-12-29 18:26:49
言語 C++11
(gcc 11.4.0)
結果
TLE  
実行時間 -
コード長 1,002 bytes
コンパイル時間 556 ms
コンパイル使用メモリ 66,332 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-08-23 09:01:52
合計ジャッジ時間 5,540 ms
ジャッジサーバーID
(参考情報)
judge13 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,380 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 2 ms
4,376 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,376 KB
testcase_07 AC 3 ms
4,376 KB
testcase_08 AC 62 ms
4,380 KB
testcase_09 AC 5 ms
4,376 KB
testcase_10 TLE -
testcase_11 -- -
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 #

//v / wが大きいほうから探索 → 分岐限定で枝刈り
#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;
	}
	if (sumV + remW * bag[id].key <= 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