hdu2546 饭卡 (dp 01背包)

链接:点我

简单01,先计算出m-5块钱在n-1个物品内最多买多少钱的菜,然后再减去最大价格的菜就行。。

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
#define max(a,b)	((a)>(b)?(a):(b))
#define inf	(0x7f7f7f7f)
const int maxn = 1005;
int main()
{
	int n, val[maxn], m, dp[maxn];
	while (scanf("%d", &n), n)
	{
		int i, j;
		for (i=0; i<n; i++)
			scanf("%d", &val[i]);
		scanf("%d", &m);
		memset(dp, 0, (m+1)*sizeof(dp[0]));
		sort(val, val+n);
		
		if (m >= 5)
		{
			for (i=0; i<n-1; i++)
			{
				for (j=m-5; j>=val[i]; j--)
				{
					dp[j] = max(dp[j], dp[j-val[i]] + val[i]);
				}
			}
			printf("%d\n", m - dp[m-5] - val[n-1]);
		}
		else
		{
			printf("%d\n", m);
		}
	}
	return 0;
}


你可能感兴趣的:(dp,ACM,01背包,hdu2546)