POJ 2576 Tug of War 背包问题

题目链接:POJ 2576 Tug of War

题目

Description

A tug of war is to be arranged at the local office picnic. For the tug of war, the picnickers must be divided into two teams. Each person must be on one team or the other; the number of people on the two teams must not differ by more than 1; the total weight of the people on each team should be as nearly equal as possible.

Input

The first line of input contains n the number of people at the picnic. n lines follow. The first line gives the weight of person 1; the second the weight of person 2; and so on. Each weight is an integer between 1 and 450. There are at most 100 people at the picnic.

Output

Your output will be a single line containing 2 numbers: the total weight of the people on one team, and the total weight of the people on the other team. If these numbers differ, give the lesser first.

Sample Input

3
100
90
200

Sample Output

190 200

分析

这题其实就是求给你 n n n个数,从中选 k k k个加起来凑成一个最接近 m m m的值。这里可以开一个bool数组,记录能否用 j j j个数凑出 i i i,虽然 n n n给了100,但是我们其实遍历到 n / 2 n/2 n/2就行了,因为限定两边差不能超过1,所以其中有一定一边是 n / 2 n/2 n/2个数。最后只要从 n / 2 n/2 n/2个数能凑出的数里选一个最接近 s u m / 2 sum/2 sum/2的即可。
代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int maxn = 450*100 + 500; 
bool dp[maxn][60];
int w[105];

int main()
{
	int n, sm = 0;
	scanf("%d", &n);
	for(int i = 1; i <= n; i++) scanf("%d", &w[i]), sm += w[i];
	int m = n >> 1, res = 1e9;
	memset(dp, false, sizeof(dp));
	dp[0][0] = true;
	for(int i = 1; i <= n; i++){
		for(int j = maxn-1; j >= 0; j--){
			for(int k = 0; k <= m; k++){
				if(dp[j][k]) dp[j+w[i]][k+1] = dp[j][k] = true;
			}
		}
	}
	for(int i = 0; i < maxn; i++)
		if(dp[i][m])
			if(abs(2*i-sm) < abs(2*res-sm)) res = i;
	printf("%d %d\n", min(res, sm-res), max(res, sm-res));
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值