ZCMU-Tug of War

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

200

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=n;p;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[n][k];
   q=sum-f[n][k];
   if(p>q)
    swap(p,q);
    printf("%d %d\n",p,q);
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值