Time Limit: 1000MS | Memory Limit: 32768KB | 64bit IO Format: %I64d & %I64u |
Description
某天,食堂中有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
#include <stdio.h>
#include <algorithm>
using namespace std;
int cmp(int a,int b)
{
return a<b;
}
int main()
{
int n;
while(~scanf("%d",&n),n)
{
int i,price[2013]= {0},dp[2013] = {0};
for(i = 1; i<=n; i++)
scanf("%d",&price[i]);
sort(price+1,price+1+n,cmp);
int MAX=price[n];
int j,m;
scanf("%d",&m);
if(m<5)//低于5元不能购买
{
printf("%d\n",m);
continue;
}
m-=5;//取出5元用于购买最贵的物品
for(i = 1; i<n; i++)//01背包
{
for(j = m;j>=price[i];j--)
{
dp[j] = max(dp[j],dp[j-price[i]]+price[i]);
}
}
printf("%d\n",m+5-dp[m]-MAX);
}
return 0;
}