您的位置:首页 > 其它

HDU 2546 饭卡 0/1背包

2014-07-29 00:47 225 查看
题目链接:HDU 2546 饭卡


饭卡

Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 10988 Accepted Submission(s): 3757



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


Source

UESTC 6th Programming Contest Online

Recommend

lcy | We have carefully selected several similar problems for you: 2955 1203 2159 1114 2639

思路:

其实就是0/1背包的问题,留下5块钱买最贵的那一个菜,然后从剩下的n-1个菜里面尽量用完总钱数减5的钱。相当于每个物品的重量和价值是一样的,现在要装满总钱数-5的袋子,求尽可能大的价值。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int main()
{
int t, n, money, price[1010], dp[1010];
while(scanf("%d", &n), n)
{
int maxp = 0, pos = 1;
for(int i = 1; i <= n; i++)
{
scanf("%d", &price[i]);
if(maxp < price[i])
{
maxp = price[i];
pos = i;
}
}
scanf("%d", &money);
if(money < 5)
{
printf("%d\n", money);
continue;
}
memset(dp, 0, sizeof(dp));
for(int i = 1; i <= n; i++)
if(pos != i)
for(int j = money-5; j >= price[i]; j--)
dp[j] = max(dp[j], dp[j-price[i]]+price[i]);
printf("%d\n", money-maxp-dp[money-5]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: