HDU-1171-Big Event in HDU(01背包的简单变形)

来源:互联网 发布:子账号登录淘宝助理 编辑:程序博客网 时间:2024/06/05 06:35

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1171

Big Event in HDU

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<N<1000) kinds of facilities (different value, different kinds).
 
Input
Input contains multiple test cases. Each test case starts with a number N (0 < N <= 50 -- the total number of different facilities). The next N lines contain an integer V (0<V<=50 --value of facility) and an integer M (0<M<=100 --corresponding number of the facilities) each. You can assume that all V are different.
A test case starting with a negative integer terminates input and this test case is not to be processed.
 
Output
For each case, print one line containing two integers A and B which denote the value of Computer College and Software College will get respectively. A and B should be as equal as possible. At the same time, you should guarantee that A is not less than B. 

Sample Input
210 120 1310 1 20 230 1-1
 
Sample Output
20 1040 40

题目分析:给出n个物体,每个物体的价值 和 具有价值的物体的数量,分成A、B两部分使A、B的价值最接近且A不小于B。  01背包变形--可以将总价值sum分成2部分。sum/2不管能不能整除,其结果都是小于实际值的。进行01背包,得到其中一部分的最大值,而另一部分的最大值一定是大于它的。
因为没看清数组范围、n的范围、还有num是从0开始计数的。。。WA了八九次敲打

代码如下:

#include<iostream>#include<algorithm>#include<cstring>using namespace std;int main(){    int n,a,b,value[5001],dp[255555];    while(cin>>n)    {        if(n<0)        break;        int i,j;        int sum=0;        int num=0;         memset(value,0,sizeof(value));        memset(dp,0,sizeof(dp));        for(i=1;i<=n;i++)        {            cin>>a>>b;            for(j=0;j<b;j++)            {                value[num]=a;//记录各个价值                 num++;//记录数量                 sum=sum+a;//记录总价值             }        }        for(i=0;i<num;i++)//一定注意!!因为num是从0开始计数的         {            for(j=sum/2;j>=value[i];j--)            {                dp[j]=max(dp[j],dp[j-value[i]]+value[i]);            }        }        cout<<sum-dp[sum/2]<<" "<<dp[sum/2]<<endl;    }    return 0;}


阅读全文
0 0
原创粉丝点击