• UVA


    Description

    Download as PDF

    Problem F: 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.

    Input

    The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.

    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

    For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.

    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

    1
    
    3
    100
    90
    200
    

    Sample Output

    190 200
    

    题意:求将人分为两部分。人数相差不超过1个,求重量差最小的可能

    思路:二维的背包会超时,可能姿势不正确。学了别人的二进制标记,dp[i]表示重量为i时的人数有几个,用<<几位表示

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    typedef long long ll;
    using namespace std;
    const int maxn = 45005;
    const int inf = 0x3f3f3f3f;
    
    ll dp[maxn];
    int w[110];
    int n, sum, mid;
    
    int main() {
    	int t;
    	scanf("%d", &t);
    	while (t--) {
    		scanf("%d", &n);
    		sum = 0;
    		for (int i = 0; i < n; i++) {
    			scanf("%d", &w[i]);
    			sum += w[i];	
    		}
    		mid = (n+1) >> 1;
    		memset(dp, 0, sizeof(dp));
    		dp[0] = 1;
    		for (int i = 0; i < n; i++)
    			for (int j = sum; j >= w[i]; j--)
    				dp[j] |= dp[j-w[i]] << 1;
    		int Min = 0, Max = inf;
    		for (int i = 0; i <= sum; i++)
    			for (int j = 0; j <= mid; j++)
    				if (dp[i] & (1ll << j) && abs(2 * j - n) <= 1) 
    					if (abs(sum - 2 * i) < Max - Min) {
    						Max = max(sum-i, i);	
    						Min = min(sum-i, i);
    					}
    		printf("%d %d
    ", Min, Max);
    		if (t)
    			printf("
    ");
    	}
    	return 0;
    }




  • 相关阅读:
    成立仅8个月的个人网站,月收入几十万美金
    Dynamics AX Bitmap to Image File
    孤儿药与长尾商品的网络营销
    How to control printer orientation(Landscape / Portrait) for an AX report in X++
    长城坑爹宽带,劫持用户DNS赚取购物返利
    2014年最大福利:185个Google排名因素!免费电子书下载
    火狐用户评价
    冲刺5
    《构建之法》阅读笔记03
    冲刺4
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/6936669.html
Copyright © 2020-2023  润新知