所谓的完全背包,就是说物品没有限制数量的。
怎么起个这么intimidating(吓人)的名字?
其实和一般01背包没多少区别,不过数量可以无穷大,那么就可以利用一个物品累加到总容量结尾就可以了。
本题要求装满的,故此增加个限制就可以了。
#include <stdio.h> #include <stdlib.h> #include <string.h> inline int min(int a, int b) { return a < b? a : b; } const int MAX_W = 10001; const int MAX_N = 501; int val[MAX_N] = {0}; int wei[MAX_N] = {0}; int tbl[MAX_W]; int bagDP(int N, int W) { for (int i = 0; i <= W; i++) tbl[i] = 0; for (int j = wei[1]; j <= W; j += wei[1]) tbl[j] = val[1] + tbl[j-wei[1]]; for (int i = 2; i <= N; i++) { for (int j = wei[i]; j <= W; j++) { if (j-wei[i]==0 || tbl[j-wei[i]]) { if (tbl[j]) tbl[j] = min(tbl[j],tbl[j-wei[i]]+val[i]); else tbl[j] = tbl[j-wei[i]]+val[i]; } } } return tbl[W]; } int main() { int E, F;//weight of an empty pig and of the pig filled with coins int T, N;// P:value, W: weight scanf("%d", &T); while (T--) { scanf("%d %d %d", &E, &F, &N); for (int i = 1; i <= N; i++) { scanf("%d %d", &val[i], &wei[i]); } int ans = bagDP(N, F-E); if (ans) printf("The minimum amount of money in the piggy-bank is %d.\n", ans); else puts("This is impossible."); } return 0; }
POJ 1384 Piggy-Bank 背包DP,布布扣,bubuko.com
原文地址:http://blog.csdn.net/kenden23/article/details/36177341