Official

C - Bento Packing Editorial by en_translator Editorial for printing


If we ignore the volume constraint, each side dish has two choices, to pack or not to pack; thus, there are a total of \(2^N\) combinations.

For each of these \(2^N\) combinations, naively calculate the total deliciousness and volume, and take the maximum total deliciousness among those whose volume does not exceed \(W\).

The time complexity is \(O(N2^N)\), which is fast enough with proper implementation.

One mainstream implementation approach is to use bitmask operations, as in the sample code below. This is sometimes called bitmask-based exhaustive search.

Sample code

#include <bits/stdc++.h>
using namespace std;
using ll = long long;

int main() {
	ll n, w;
	cin >> n >> w;
	vector<ll> a(n), b(n);
	for (int i = 0; i < n; i++) cin >> a[i] >> b[i];
	ll ans = 0;
	for (int i = 0; i < 1 << n; i++) {
		ll value = 0, cost = 0;
		for (int j = 0; j < n; j++) if (i >> j & 1) value += a[j], cost += b[j];
		if (cost <= w && ans < value) ans = value;
	}
	cout << ans << '\n';
}

posted:
last update: