HDU 1114 - Piggy-Bank

题目描述

Piggy-Bank

解法:完全背包

完全背包问题是求价值最大,而根据题意要求价值最小,故做下面两个变化:

  • 初始化,将 d p [ 1... v ] dp[1...v] 设成 \infty d p [ 0 ] = 0 dp[0]=0
  • 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;
}
发布了152 篇原创文章 · 获赞 22 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_38204302/article/details/105194076