题目描述
解法:完全背包
完全背包问题是求价值最大,而根据题意要求价值最小,故做下面两个变化:
- 初始化,将 设成 ,
- max 换成 min
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
int main()
{
int dp[10010];
int t, e, f, n, p, w, v;
cin >> t;
for(int i=0;i<t;i++)
{
memset(dp, 0x7f, sizeof(dp));
dp[0] = 0;
cin >> e >> f;
v = f-e;
cin >> n;
for(int j=1;j<=n;j++)
{
cin >> p >> w;
for(int k=w;k<=v;k++)
{
dp[k] = min(dp[k], dp[k-w]+p);
}
}
if(dp[v]!=dp[10009])
{
cout << "The minimum amount of money in the piggy-bank is " << dp[v] << "." << endl;
}
else
{
cout << "This is impossible." << endl;
}
}
return 0;
}