Light oj 1147 - Tug of War(状压dp)

本文介绍了一种解决拔河比赛分组问题的算法。该问题要求将参赛者分为两个团队,使团队间的体重差距最小,同时确保团队人数相差不超过一人。通过动态规划方法实现了最优分配,最终输出两组体重总和最接近的分组方案。

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

1147 - Tug of War
Time Limit: 4 second(s)Memory Limit: 32 MB

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

Input starts with an integer T (≤ 100), denoting the number of test cases.

The first line of each case is a blank line. The next line of input contains an integer n (2 ≤ n ≤ 100), 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 100000. The summation of all the weights of the people in a case will not exceed 100000.

Output

For each case, print the case number and the total number weights of the people in two teams. If the weights differ, print the smaller weight first.

Sample Input

Output for Sample Input

2

 

3

100

90

200

 

4

10

15

17

20

Case 1: 190 200

Case 2: 30 32

 


SPECIAL THANKS: JANE ALAM JAN (SOLUTION, DATASET)
1147 - Tug of War


/*

题意:有n个人,每个人都由重量。现将其分成人数差小于等于1的两组,求两组各自总质量之差最小的组合。
题解:动态规划,dp[i]=m,其中i为重量,m为二进制,
其第k位为1表示可以由 k个人组合使得总质量为i。之后就是01背包了。
//上面一句是重点

*/

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<map>

#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define MID(x,y) ((x+y)>>1)

#define bug printf("hihi\n")

#define eps 1e-8
typedef long long ll;

using namespace std;

#define INF 0x3f3f3f3f
#define N 100005

ll dp[N];
int a[105];
int all;
int n;

bool judge(int m)
{
    ll ha=dp[m];
    int t=n/2;
    if(n&1)
        return (ha&(1ll<<t)||(ha&(1ll<<(t+1))));
    return (ha&(1ll<<t));
}

int main()
{
    int i,j,t,ca=0;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        all=0;
        for(i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            all+=a[i];
        }
        memset(dp,0,sizeof(dp));
        int m=all/2;
        dp[0]=1;
        for(i=1;i<=n;i++)
        {
             for(int v=m;v>=a[i];v--)
                  dp[v]=dp[v]|((ll)dp[v-a[i]]<<1);
        }

        for(i=m;i>=0;i--)
            if(judge(i))
        {
              printf("Case %d: %d %d\n",++ca,i,all-i);
              break;
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值