多重背包,但由于是bool型,可以使用特殊方法优化效率使得效率与01背包相同
View Code
#include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> using namespace std; #define maxn 15 #define maxc 100005 int cash; int n; int num[maxn], denomination[maxn]; bool f[maxc]; int used[maxc]; void input() { scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d%d", &num[i], &denomination[i]); } void work() { memset(f, 0, sizeof(f)); f[0] = true; for (int i = 0; i < n; i++) { memset(used, 0, sizeof(used)); for (int j = denomination[i]; j <= cash; j++) if (f[j - denomination[i]] && !f[j] && used[j - denomination[i]] < num[i]) { f[j] = true; used[j] = used[j - denomination[i]] + 1; } } } int main() { //freopen("t.txt", "r", stdin); while (~scanf("%d", &cash)) { input(); work(); for (int i = cash; i >= 0; i--) if (f[i]) { printf("%d\n", i); break; } } return 0; }