POJ 1276 Cash Machine(多重背包)

本题完全模仿《背包问题九讲》。一会儿去好好学习下背包问题。注明一点,cost和weight是一样的,可以省略一个参数和一个数组(我没省)。不能多说了。贴上我微弱的代码:

   1: #include <iostream>
   2: #include <algorithm>
   3: #include <memory.h>
   4: using namespace std;
   5: const int CASH_SIZE = 100001;
   6: const int D_SIZE = 1001;
   7: int volume;
   8: int f[CASH_SIZE], costArr[D_SIZE], weightArr[D_SIZE], amountArr[D_SIZE];
   9:  
  10: void ZeroOnePack(int cost, int weight)
  11: {
  12:     for (int v=volume; v>=cost; v--)
  13:         f[v]=max(f[v], f[v-cost]+weight);
  14: }
  15:  
  16: void CompletePack(int cost, int weight, int i)
  17: {
  18:     for (int v=cost; v<=volume; v++)
  19:         f[v]=max(f[v],f[v-costArr[i]]+weightArr[i]);
  20: }
  21:  
  22: void MultiplePack(int cost, int weight, int amount, int i)
  23: {
  24:     if (cost*amount>=volume)
  25:     {
  26:         CompletePack(cost, weight, i);
  27:         return;
  28:     }
  29:     int k=1;
  30:     while (k<amount)
  31:     {
  32:         ZeroOnePack(k*cost, k*weight);
  33:         amount -= k;
  34:         k <<= 1;
  35:     }
  36:     ZeroOnePack(amount*cost, amount*weight);
  37: }
  38:  
  39: int main()
  40: {
  41:     int n=0; 
  42:     while (cin >> volume >> n)
  43:     {
  44:         memset(f, 0, sizeof(f));
  45:         memset(weightArr, 0, sizeof(weightArr));
  46:         memset(costArr, 0, sizeof(costArr));
  47:         for (int i=0; i<n; i++)
  48:         {
  49:             cin >> amountArr[i] >> costArr[i];
  50:             weightArr[i] = costArr[i];
  51:         }
  52:         for (int i=0; i<n; i++)
  53:         {
  54:             MultiplePack(costArr[i], weightArr[i], amountArr[i], i);
  55:         }
  56:         cout << f[volume] << endl;
  57:     }
  58:     return 0;
  59: }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值