【算法】Tug of War-动态规划

Tug of War

总时间限制: 3000ms 内存限制: 65536kB

描述
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.
输入
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.
输出
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.
样例输入
3
100
90
200
样例输出
190 200

# include<iostream>
# include<string.h>
using namespace std;
 
# define N 105
# define W N*450/2+1
 
//任意n个人能否满足w的体重,0表示不能,1表示能
int dp[N][W];
 
int main()
{
    int n,sw=0,w[N],i,j,k;
 
    cin>>n;
    for(i=1;i<=n;i++)
    {
        cin>>w[i];
        sw+=w[i];
        dp[i][0]=1;
        dp[0][i]=0;
    }
 
 
    dp[0][0]=1;
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=sw/2+1;j++)
        {
            for(k=1;k<=n;k++) //对n个人依次扫描
            {
                if(j-w[k]>=0 && dp[i-1][j-w[k]]==1)
                {
                    dp[i][j]=1;
                    break;
                }
            }
        }
    }
 
 
    if(n%2==0)
    {
        for(i=sw/2;i>=1;i--)
        {
            if(dp[n/2][i]==1)
            {
                k=i;
                break;
            }
        }
        cout<<min(k,sw-k)<<" "<<max(k,sw-k)<<endl;
    }
    else
    {
        for(i=sw/2;i>=1;i--)
        {
            if(dp[n/2][i]==1 || dp[n/2+1][i]==1)
            {
                k=i;
                break;
            }
        }
        cout<<min(k,sw-k)<<" "<<max(k,sw-k)<<endl;
    }
 
 
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值