您的位置:首页 > 其它

二维费用背包(不错)--poj2576

2013-09-05 21:51 239 查看
Language:
Default

Tug of War

Time Limit: 3000MS

Memory Limit: 65536K

Total Submissions: 8023

Accepted: 2153

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<cmath>
#include<cstring>
using namespace std;
int f[105];
int dp[50000][105];
int main()
{
    int n;
    int sum;
    while(cin>>n)
    {
        sum=0;
        for(int i=1; i<=n; i++)
        {
            cin>>f[i];
            sum+=f[i];
        }
        int mid=sum/2;
        int half=(n+1)/2;
        memset(dp,0,sizeof(dp));
        dp[0][0]=1;
        for(int i=1; i<=n; i++)
            for(int j=mid; j>=f[i]; j--)
                for(int k=half; k>0; k--)
                    if(dp[j-f[i]][k-1])
                        dp[j][k]=1;
        int max1=0;
        int j;
        for(j=mid; j>=0; j--)
            if(dp[j][half]||dp[j][half-1])
                break;

        cout<<j<<' '<<sum-j<<endl;
    }
    return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: