hdu 1171 多重背包

http://acm.hdu.edu.cn/showproblem.php?pid=1171

这道题题意很简单: n台机器,每台机器两个属性,一个Value 另一个数量,要平均分,使得A>=B;

(1)首先先说一下背包思路:  在输入的时候先求出 总的 sum=Value1*amount1+Value2*amount2+Value3*amount3........z

接下来:

背包容量为 sum/2,对所有机器背包,就行了。这个时候dp[sum/2] 的值就是不超过sum的一半的最大值,那么A=sum-dp[sum/2],B=dp[sum/2];

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <algorithm>
using namespace std;
const int MAX = 250000+100;
int cost[100],amount[100];
int f[MAX],v;
void ZeroOnePack(int cost,int weight)
{
    int i;
    for(i=v;i>=cost;i--)
    {
        f[i] = max(f[i],f[i-cost]+weight);
    }
}
void CompletePack(int cost,int weight)
{
    int i;
    for(i=cost;i<=v;i++)
    {
        f[i] = max(f[i],f[i-cost]+weight);
    }
}
void MultiplePack(int cost,int weight,int amount)
{
    if(v <= cost*amount)
    {
        CompletePack(cost,weight);
        return;
    }
    else
    {
        int k = 1;
        while(k<amount)
        {
            ZeroOnePack(k*cost,k*weight);
            amount = amount - k;
            k = k*2;
        }
        ZeroOnePack(amount*cost,amount*weight);
    }
}
int main()
{
 int n;
 while(cin>>n&&n>=0)
 {
  memset(f,0,sizeof(f));
  int sum=0;
  for(int i=1;i<=n;i++)
  {
    cin>>cost[i]>>amount[i];
    sum+=cost[i]*amount[i];
  }
  v=sum/2;
  for(int i=1;i<=n;i++)
    MultiplePack(cost[i],cost[i],amount[i]);
  cout<<sum-f[v]<<" "<<f[v]<<endl;
 }
 return 0;
}
(2)还有第二种思路,不是背包,也不是母函数啥的。

1.有点像贪心,将所有value 从小到大排序,并且求出sum,令half=sum/2;    

2.然后从最右边往左边扫,初始化cnt=0;  

int cnt=0;
for(int i=n;i>=1;i--) 
  if(cnt>half)
    continue;
  else
     cnt+=a[i]
//这样得到的cnt就是 B。。。 A就是sum-cnt;


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值