hud 1171 Big Event in HDU(基础0_1背包)

来源:互联网 发布:淘宝买东西安装工人 编辑:程序博客网 时间:2024/05/12 16:54

原题链接
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
2
10 1
20 1
3
10 1
20 2
30 1
-1

Sample Output
20 10
40 40

题目大意:给你一个n代表有n个物品,随后又n行表示每个物品的价值和数量,要求输出将这些物品分成两份后的价值,如果可以均分就均分否则就让第一份比第二份多。

解题思路:用0_1 背包的思路,将背包总容量等价于所有物品价值总和的一半,没有物品的价值和重量相等。每个物品分去或者不取。

#include <bits/stdc++.h>#define INF 0x3f3f3f3fusing namespace std;int dp[255555];int v[5100];int main(){    int n,S,Count,value,num,sum;    while(~scanf("%d",&n))    {        if(n<0)break;        S = 0;        Count = 0;        for(int i=1;i<=n;i++){            scanf("%d %d",&value,&num);            for(int j = 1;j <= num; j++){                S += value;                v[++Count] = value;//记录每个物品的价值            }        }        sum = S/2;//将背包的总容量设为所有物品价值总和的一半        memset(dp,0,sizeof(dp));        for(int i = 1; i <= Count; i++){            for(int j = sum; j >= v[i]; j --)//价值和重量相等                dp[j] = max(dp[j],dp[j-v[i]] + v[i]);        }        printf("%d %d\n",S-dp[sum],dp[sum]);    }    return 0;}
阅读全文
0 0
原创粉丝点击