POJ 1384 Piggy-Bank 背包DP

时间:2022-07-09 12:15:02

所谓的全然背包,就是说物品没有限制数量的。

怎么起个这么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;
}