http://acm.hdu.edu.cn/showproblem.php?pid=2639
参考背包九讲9.5节,注意合并单调队列的技巧(末尾加一个-1标记)
完整代码:
/*109ms,488KB*/ #include<cstdio> #include<cstring> #include<algorithm> #include<functional> using namespace std; int w[105], v[105], dp[1005][65], tmp1[35], tmp2[35]; ///a+b->c,集合去重型合并,按从大到小的顺序 void set_unique_union(int a[], int b[], int c[], int k) { int x = 1, y = 1, z = 1;///便于判重 while (z <= k && (a[x] >= 0 || b[y] >= 0)) { c[z] = (a[x] > b[y] ? a[x++] : b[y++]); if (c[z] != c[z - 1]) ++z; } } int _01pack(int n, int maxw, int k) { memset(dp, 0, sizeof(dp)); memset(tmp1, 0, sizeof(tmp1)); memset(tmp2, 0, sizeof(tmp2)); int i, j, p, x, y, z; for (i = 0; i < n; ++i) { for (j = maxw; j >= w[i]; --j) { memcpy(tmp1 + 1, dp[j] + 1, sizeof(int) * k); for (p = 1; p <= k; ++p) tmp2[p] = dp[j - w[i]][p] + v[i]; tmp1[k + 1] = tmp2[k + 1] = -1; set_unique_union(tmp1, tmp2, dp[j], k); } } return dp[maxw][k]; } int main() { int t, n, maxw, i, k; scanf("%d", &t); while (t--) { scanf("%d%d%d", &n, &maxw, &k); for (i = 0; i < n; ++i) scanf("%d", &v[i]); for (i = 0; i < n; ++i) scanf("%d", &w[i]); printf("%d\n", _01pack(n, maxw, k)); } return 0; }