HDOJ_ACM_饭卡

Problem Description
电子科大本部食堂的饭卡有一种很诡异的设计,即在购买之前判断余额。如果购买一个商品之前,卡上的剩余金额大于或等于5元,就一定可以购买成功(即使购买后卡上余额为负),否则无法购买(即使金额足够)。所以大家都希望尽量使卡上的余额最少。
某天,食堂中有n种菜出售,每种菜可购买一次。已知每种菜的价格以及卡上的余额,问最少可使卡上的余额为多少。
 
Input
多组数据。对于每组数据:
第一行为正整数n,表示菜的数量。n<=1000。
第二行包括n个正整数,表示每种菜的价格。价格不超过50。
第三行包括一个正整数m,表示卡上的余额。m<=1000。

n=0表示数据结束。
 
Output

            对于每组输入,输出一行,包含一个整数,表示卡上可能的最小余额。
 
Sample Input
1
50
5
10
1 2 3 2 1 1 2 3 2 1
50
0
 
Sample Output
-45
32
 
 
Code
 
View Code 
View Code        
Key Point
For this question, you should translate the condition and realize that leave the 5 RMB for the most expensive dish.
Then using 0/1 knapsack to get the greatest value by the remainder money. 
Lastly, it's the answer that your moeny minus the greatest value, minus the most expensive dish price.
 
Note, you must care about the money is below 5 RMB.
 
对于这个问题,你要转换条件,意识到只需留下5元给最贵的食物,然后,用剩下的钱使用0/1背包得到最大价值,最后,钱-最大价值-最贵的食物,就是答案。
 
另外还得注意少于5元的情况.

And I update the second method to get the answer, which perform faster and uses less memory.

The price is lower than 50 RMB, so you can use multiply knapsack, which is samiliar to the before question.

更新了第二种方法,能更快且使用更少内存得到答案,因为考虑到价格是低于50元的,所以可以采用类似于之前那道题目的多重背包来解题。

原文地址:https://www.cnblogs.com/chuanlong/p/2812551.html