题目:
http://acm.hdu.edu.cn/showproblem.php?pid=1114
题意:
给定存钱罐的初始重量和装满硬币后的重量,给出每种硬币的价值和重量,问存钱罐装满后可能的最小价值是多少
思路:
每种硬币的数量都不限制,因此是个完全背包。初始化dp数组时需注意,因为求的最小,且题目的意思是恰好装满,所以dp数组初始化为INF,但dp[0] = 0,意为此时只有容量为0 的背包可以在什么也不装且价值为0 的情况下被“恰好装满”,其它容量的背包均没有合法的解,属于未定义的状态(背包九讲)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 10010, INF = 0x3f3f3f3f;
int dp[N];
int w[N], v[N];
int main()
{
int t, n, a, b;
scanf("%d", &t);
while(t--)
{
scanf("%d%d", &a, &b);
int W = b - a;
scanf("%d", &n);
for(int i = 1; i <= n; i++) scanf("%d%d", &v[i], &w[i]);
memset(dp, 0x3f, sizeof dp);
dp[0] = 0;
for(int i = 1; i <= n; i++)
for(int j = w[i]; j <= W; j++)
dp[j] = min(dp[j], dp[j-w[i]] + v[i]);
if(dp[W] == INF) printf("This is impossible.\n");
else printf("The minimum amount of money in the piggy-bank is %d.\n", dp[W]);
}
return 0;
}