0-1背包问题之——饭卡

电子科大本部食堂的饭卡有一种很诡异的设计,即在购买之前判断余额。如果购买一个商品之前,卡上的剩余金额大于或等于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

  // 最基本的是根据0—1背包问题来解决的。详细解释在注释中
  //这是没有空间优化过的代码,若total与n很大,则必须要空间优化。优化方法请看文章:Bone Collector
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
#define maxn 105
int money[105*10];
int f[maxn*10][maxn*10];
int last(int n,int total)
{
    sort(money+1,money+n+1);//排序之后可以得到价格最大的money[n];
//用背包思想得出小于total-5之中的最大值,即尽可能让值接近total-5; for(int i = 1; i < n; i++) { for(int j = 0 ; j <= total - 5; j++) { if(j < money[i]) f[i][j] = f[i-1][j]; else f[i][j] = max(f[i - 1][j],f[i -1][j - money[i]] + money[i]); } } int ans = 0;
//选出接近total-5的最大值 for(int v = 0; v <= total - 5; v++) { ans = max(f[n-1][v],ans); } return total-(ans+money[n]);//将total减去最接近total-5和最大价值的money[n],得到最后卡上最小的余额。 } int main() { int n,total; while(cin>>n && n) { memset(money,0,sizeof(money)); memset(f,0,sizeof(f)); for(int i = 1; i <= n; i++) { cin>>money[i]; } cin>>total; if (total<5) cout<<total<<endl; //隐含的条件,这句话不能少!!! else cout<<last(n,total)<<endl; } return 0; }
原文地址:https://www.cnblogs.com/T8023Y/p/3230024.html