【多维背包】——poj2576——天平背问题

                                             Tug of War

Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 8904   Accepted: 2468

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<iostream>
#include<string.h>
using namespace std;

int w[105];
int dp[30000][55];

int main()
{
    int n;
    cin>>n;
    int sum=0;
    for(int i=0;i<n;i++)
    {
        cin>>w[i];
        sum+=w[i];
    }

    int s=sum/2;
    int h=(n+1)/2;
    memset(dp,-1,sizeof(dp));
    dp[0][0]=0;

    int ans1=-1;
    for(int i=0;i<n;i++)
    {
        for(int j=s;j>=w[i];j--)
        {
            for(int k=h;k>=1;k--)
            {
                if(dp[j-w[i]][k-1]!=-1)
                    dp[j][k]=max(dp[j][k],dp[j-w[i]][k-1]+w[i]);

                ans1=max(dp[j][k],ans1);
            }
        }
    }

    cout<<min(ans1,sum-ans1)<<" "<<max(ans1,sum-ans1)<<endl;

    return 0;
}

 

posted @ 2016-08-21 22:12  琥珀川||雨露晨曦  阅读(200)  评论(0)    收藏  举报