您的位置:首页 > 其它

ZCMU-Tug of War

2017-01-24 21:46 369 查看

Problem D: Problem D: Tug of War

Time Limit: 10 Sec  Memory Limit: 128 MB
Submit: 42  Solved: 17

[Submit][Status][Web
Board]

Description

Problem D: Tug of War

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.

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.

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.

Input

Output

Sample Input

3

100

90

20
4000
0

Sample Output

190 200

【解析】
此题的意思就是给你n个人,叫你分两组,两组当中相差的人数最多只能是1,然后需要让两个组当中的人体重相差最
少,这是一场拔河比赛。我们先要把所有的体重都加起来。然后把它折合成一半,其实就是背包问题,最大体重上限
设置为体重的一半,然后人数的话,如果总人数是偶数,那人数就分成一半,否则就分成一半+1,因为是整数向下除
整。这里我们设置二维数组f[i][j],这里j代表的是体重上限,而i则是代表这个时候有多少人。其实状态转移方程
就是f[i][j]=max(f[i][j],f[i-1][j-a[i]]),其实和01背包问题是相似的。还要注意的是把小的体重先输出,再输出大
的。
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
int f[101][22500];
int main()
{
int a[101];
int n,i,sum=0,m,k,p,j,q;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];//计算总的体重
}
k=sum/2;//体重的一半
m=n;
if(n%2==0)
n=n/2;//算出一半有多少人
else
n=n/2+1;
for(i=0;i<m;i++)
{
for(p=1;p<=n;p++)
{
for(j=k;j>=a[i];j--)
{
f[p][j]=max(f[p][j],f[p-1][j-a[i]]+a[i]);//计算一半人最大的体重
}
}
}
p=f
[k];
q=sum-f
[k];
if(p>q)
swap(p,q);
printf("%d %d\n",p,q);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: