POJ 2576 Tug of War

本文介绍了一个经典的算法问题:如何将一组具有不同重量的人分成两个队伍,使得两队人数之差不超过1且总重量尽可能接近。文章通过动态规划的方法解决了这个问题,并提供了一段完整的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Tug of War
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 8892 Accepted: 2463

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

Source

Waterloo local 2000.09.30


题意:有n个数,将这n个数分成两份,这两份的数量相差不能超过1,总和要尽可能相等,要求每个数都要选到

考虑动规的思想,f[i][j]表示选i个人,能否使总和到达j

显然,讨论到第s个人的时候,如果f[i][j]=1,那么f[i+1][j+value[s]]=1

这里对i和j都是有限制的,i<=(n+1)/2,j<=sum/2

这里有一个小细节,如果把i的范围换成i<=n/2是不行的,想一想为什么

#include<cstdio>
#include<iostream>
using namespace std;
const int maxn=105,inf=1e9,maxm=455;
inline void _read(int &x){
    char t=getchar();bool sign=true;
    while(t<'0'||t>'9')
    {if(t=='-')sign=false;t=getchar();}
    for(x=0;t>='0'&&t<='9';t=getchar())x=x*10+t-'0';
    if(!sign)x=-x;
}
int n,s[maxn];
bool f[maxn][maxn*maxm];
int main(){
	int i,j,halfm,halfn,sum=0,k,ans;
	cin>>n;
	for(i=1;i<=n;i++){
		cin>>s[i];
		sum+=s[i];
	}
	halfm=sum/2;
	halfn=(n+1)/2;
	for(i=0;i<=halfn;i++)f[i][0]=1;//初始化
	for(i=1;i<=n;i++)
	    for(j=0;j<=halfn;j++)
	        for(k=0;k+s[i]<=halfm;k++)
	            if(f[j][k])
	                f[j+1][k+s[i]]=1;
	ans=halfm;
	while(!f[halfn][ans])ans--;
	int anss=sum-ans;
	if(anss>ans)swap(anss,ans);
	cout<<anss<<" "<<ans;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值