题目描述
解法:完全背包
完全背包问题是求价值最大,而根据题意要求价值最小,故做下面两个变化:
- 初始化,将 d p [ 1... v ] dp[1...v] dp[1...v]设成 ∞ \infty ∞, d p [ 0 ] = 0 dp[0]=0 dp[0]=0
- m a x max max 换成 m i n min min
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
int main()
{
int t, n, f, e, v, p, w;
int dp[10010];
cin >> t;
for(int tt=0;tt<t;tt++)
{
memset(dp, 0x7f, sizeof(dp));
dp[0] = 0;
cin >> e >> f;
v = f-e;
cin >> n;
for(int i=1;i<=n;i++)
{
cin >> p >> w;
for(int j=w;j<=v;j++) dp[j] = min(dp[j], dp[j-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;
}