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

来源:互联网 发布:中国的hiv 知乎 编辑:程序博客网 时间:2024/05/27 00:32

原题: 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