poj 2576 简单 二维背包

本文介绍了一个经典的体重分配问题——Tug of War。该问题要求将n个人分成两组进行拔河比赛,使得两组的人数差不超过1且总重量尽可能接近。通过使用动态规划的方法,文章提供了一种有效的解决方案,并附带了完整的C语言代码实现。

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

题目要求:

n个人,每个人体重x[i],让你把他们分成两组,两组之间的人数差不能大于1。输出两组体重差最小的情况


Tug of War
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 7419 Accepted: 1956

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

#include<stdio.h>
#include<string.h>
int dp[45110][115];
int w[115];
int main()
{
    int i,j,k,l,m,n,sum,r;
   // scanf("%d",&m);
    while(scanf("%d",&n)!=EOF)
    {
        sum=0;
        r=(n+1)>>1;
        for(i=0; i<n; i++)
        {
            scanf("%d",&w[i]);
            sum+=w[i];
        }
        memset(dp,0,sizeof(dp));
        dp[0][0]=1;
        for(i=0; i<n; i++)
        {
            for(j=sum/2; j>=w[i]; j--)
            {
                for(k=r; k>=1; k--)
                {
                    if(dp[j-w[i]][k-1]==1)
                        dp[j][k]=1;
                }
            }
        }
        for(i=sum/2; i>=0; i--)
        {
            if(n%2==0)
            {
                if(dp[i][r]==1)
                    break;
            }
            else
            {
                if(dp[i][r]==1||dp[i][r-1]==1)
                    break;
            }
        }
        printf("%d %d\n",i,sum-i);
    }
    return 0;
}

/*
3
100
90
200
*/



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值