链接
http://acm.hdu.edu.cn/showproblem.php?pid=1114
题意
现在你有一个存钱罐,你已经知道它不装硬币时的重量
W
1
W_1
W1和装满硬币时的重量
W
2
W_2
W2,现在你有
n
n
n种硬币,第
i
i
i种硬币有对应的价格
p
i
p_i
pi以及对应的重量,一种硬币可以选多次,现在问你将存钱罐装满硬币,所需要的最小硬币价格和,如果不能恰好装满
,那么输出This is impossible.
,否则输出The minimum amount of money in the piggy-bank is 60.
,将你得到的和与60替换;
分析
这是一个完全背包,首先对于求最小值,我们需要将 d p dp dp数组初始为 ∞ \infty ∞, d p [ x ] dp[x] dp[x]表示存钱罐装硬币重量为 x x x,所需要最小硬币价格和,那么显然我们需要初始化 d p [ 0 ] = 0 dp[0]=0 dp[0]=0;然后完全背包求解即可,最后看 d p [ W 2 − W 1 ] dp[W_2-W_1] dp[W2−W1]是否等于 ∞ \infty ∞,若等于显然,不能用硬币将存钱罐恰好装满,否则输出结果;
代码
#include <algorithm>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <set>
#include <map>
#define INF 0x7f7f7f7f
#define MAXN 100005
#define N 200005
#define P 2
#define MOD 99991
typedef long long ll;
namespace fastIO {
#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1<<22, stdin), p1 == p2) ? EOF : *p1++)
char buf[(1 << 22)], *p1 = buf, *p2 = buf;
inline int read() {
char c = getchar(); int x = 0, f = 1;
while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); }
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
}
using namespace fastIO;
using namespace std;
int t, n, m, dp[10008], p[502], w[505];
int e, f;
int main() {
cin >> t;
while (t--) {
cin >> e >> f;
f -= e;
cin >> n;
for (int i = 1; i <= n; i++)
cin >> p[i] >> w[i];
memset(dp, INF, sizeof(dp));
dp[0] = 0;
// 这里要求使用若干个物品将背包恰好填充满的最小价值
for (int i = 1; i <= n; i++)
for (int j = w[i]; j <= f; j++)
dp[j] = min(dp[j], dp[j - w[i]] + p[i]);
if (dp[f] == INF)cout << "This is impossible." << endl;
else cout << "The minimum amount of money in the piggy-bank is "<< dp[f] << "." << endl;
}
}