题解
直接将m减去n得到硬币重量 d[i]表示容量为i的时候最小的价值 使用多重背包dp求解 区别在于每次取min
AC代码
#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int MAXN = 5e2 + 10;
const int MAXM = 1e4 + 10;
int d[MAXM]; //容量为i的时候最小价值
int p[MAXN], w[MAXN]; // 价值 重量
int main()
{
#ifdef LOCAL
freopen("C:/input.txt", "r", stdin);
#endif
int T;
cin >> T;
while (T--)
{
memset(d, 0x3f, sizeof(d));
int n, m;
cin >> n >> m;
m -= n;
cin >> n;
for (int i = 1; i <= n; i++)
scanf("%d%d", &p[i], &w[i]);
d[0] = 0;
for (int i = 1; i <= n; i++)
{
for (int j = w[i]; j <= m; j++)
if (d[j - w[i]] < INF) //是有效状态
d[j] = min(d[j], d[j - w[i]] + p[i]);
}
if (d[m] < INF)
printf("The minimum amount of money in the piggy-bank is %d.\n", d[m]);
else
printf("This is impossible.\n");
}
return 0;
}