HDU 1171 Big Event in HDU 多重背包01求解

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

题目:

Big Event in HDU

Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 29440 Accepted Submission(s): 10341

Problem Description
Nowadays, we all know that Computer College is the biggest department in HDU. But, maybe you don’t know that Computer College had ever been split into Computer College and Software College in 2002.
The splitting is absolutely a big event in HDU! At the same time, it is a trouble thing too. All facilities must go halves. First, all facilities are assessed, and two facilities are thought to be same if they have the same value. It is assumed that there is N (0

思路:

给定物品的价值和数目,尽量平均分给两个人。其实就是让其中一个人挑选物品,让物品的价值尽量接近总价值的一半。

其实就是一个多重背包问题,对于这种简单的数据量小的问题,如果我们把相同的物品看作不同物品,就可以把题目理解成所有物品只能选一次,我们可以用01背包的方式求解。

代码:

#include <iostream>
#include"string.h"
#include"cstdio"
#include"stdlib.h"
#include"algorithm"
using namespace std;


int zong;
const int N = 50050;  //最大件数
const int M = 50050;  //最大重量
int weight[N];
int dp[M];
int NN,W;

void init()
{
    NN=0;
    zong=1;
    memset(weight,0,sizeof(weight));
    memset(dp,0,sizeof(dp));
}
int backpack()
{
    for(int i=1;i<=NN;i++)   //当前放的件数
    {
        for(int j=W;j>=0;j--)   //当前重量
        {
            if(j<weight[i])
                dp[j]=dp[j];
            if(j>=weight[i])
            dp[j]=max(dp[j],dp[j-weight[i]]+weight[i]);
        }
    }
}


int main()
{
    int n;
    while(scanf("%d",&n))
    {
    if(n<0) break;
    if(n==0)    continue;
    init();
    int sum=0;
    for(int i=1;i<=n;i++)
    {
        int val,shumu;
        scanf("%d %d",&val,&shumu);
        NN=NN+shumu;            //求得物品总件数
        for(int j=0;j<shumu;j++)
        {
            weight[zong]=val;   //把相同的物品按不同物品考虑存入
            zong++;
            sum=sum+val;        //求得总价值
        }
    }
    W=sum/2;
    backpack();
    printf("%d %d\n",sum-dp[W],dp[W]);  //后着总是会<=前者的
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值