题目链接: 点击打开链接
题目大意: 给定重量上限,求刚好填满这个上限的所有硬币的最小价值。
思路: 动态规划,完全背包
分析:
完全背包基础题,用一维数组,先遍历所有种类的硬币,接着从小到大遍历重量,转移方程为 dp[i][j] = min( dp[i-1][j], dp[i][j-weight[i] ] + value[i] )。
代码:
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxw = 10000 + 10;
const int maxn = 500 + 10;
const int INF = 999999999;
int e, f, n, p[maxn], w[maxn], dp[maxw];
void solve()
{
int weight = f - e;
for (int i = 1; i <= weight; ++i)
dp[i] = INF;
dp[0] = 0;
for (int i = 1; i <= n; ++i)
for (int j = w[i]; j <= weight; ++j)
dp[j] = min(dp[j], dp[j-w[i]]+p[i]);
}
void output()
{
if (dp[f-e] != INF)
printf("The minimum amount of money in the piggy-bank is %d.\n", dp[f-e]);
else
printf("This is impossible.\n");
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
scanf("%d %d %d", &e, &f, &n);
for (int i = 1; i <= n; ++i)
scanf("%d %d", &p[i], &w[i]);
solve();
output();
}
return 0;
}