完全背包问题。
f[i][j]表示用前j个物品,放满i的空间,能取得最大价值。 f[i][j] =max f[i - a[P]]j - 1] + b[P]
j按顺序用的话,数组第二维可以压掉。即为f[i] = max f[i - a[P]] + b[P]
Executing... Test 1: TEST OK [0.008 secs, 3484 KB] Test 2: TEST OK [0.008 secs, 3484 KB] Test 3: TEST OK [0.008 secs, 3484 KB] Test 4: TEST OK [0.005 secs, 3484 KB] Test 5: TEST OK [0.019 secs, 3484 KB] Test 6: TEST OK [0.032 secs, 3484 KB] Test 7: TEST OK [0.057 secs, 3484 KB] Test 8: TEST OK [0.119 secs, 3484 KB] Test 9: TEST OK [0.230 secs, 3484 KB] Test 10: TEST OK [0.221 secs, 3484 KB] Test 11: TEST OK [0.003 secs, 3484 KB] Test 12: TEST OK [0.003 secs, 3484 KB] All tests OK.
n^2的算法居然挺快的。
大量读入,getcahr目测要快更多?
/* TASK:inflate LANG:C++ */ #include <cstdio> #include <cstring> #define max(a,b) ((a)>(b)?(a):(b)) int m, n; int a[10001], b[10001]; int c[10001], ans = -1; int main() { freopen("inflate.in","r",stdin); freopen("inflate.out","w",stdout); scanf("%d%d", &m, &n); for (int i = 0; i != n; ++ i) scanf("%d%d", &a[i], &b[i]);//价值 体积 memset(c, -1, sizeof(c)); c[0] = 0; for (int i = 0; i != n; ++ i) for (int j = 0; j <= m-b[i]; ++ j) { if (c[j]!=-1) { c[j+b[i]] = max(c[j+b[i]], c[j] + a[i]); ans = max(c[j + b[i]], ans); } } printf("%d\n", ans); return 0; }