hdu1171(01和多重背包问题)

hdu1171(背包问题)

多重背包转化为01背包

题目描述:
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 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.

输出:
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种设施分成两部分,每种设施的价值为v,数量为m,需要将其价值分成相差尽量少的两份,输出的第一份的价值不少于第二份。

解题思路:对于每种设施,对于一个学院来说,我们需要判断每种设施需要拿多少,然后尽量接近总价值的一半。观察到n,v,m都足够小,可以转化为01背包去解决,然后只要算出第二份的最大值,而第二份的最大值的上限是sum/2,所以就可以简单的通过01背包解决此问题了。

代码:

#include<bits/stdc++.h>
using namespace std;
int dp[250010];
int a[5010];
int main(){
	int n;
	while(cin >> n && n>=0){
		memset(dp,0,sizeof(dp));
		memset(a,0,sizeof(a));
		int x, y;
		int t=0;
		int sum=0;
		for(int i=0;i<n;i++){             //转化成01背包 
			cin >> x >> y;
			for(int j=0;j<y;j++){
				a[t++]=x;
				sum+=x;
			}
		}
		for(int i=0;i<t;i++){
			for(int j=sum/2;j>=a[i];j--){
				dp[j]=max(dp[j],dp[j-a[i]]+a[i]);
			}
		}
		cout << sum-dp[sum/2] << " " << dp[sum/2] << endl;     //算出第二份的最大值后,第一份的值即为sum-dp[sum/2] 
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值