poj2148(二维背包)

题意:有n个奶牛,每个都有一个s和t值,取奶牛的一个子集并在保证s之和与t之和均大于等于0的情况下,求∑(s+t)最大;


解法:将二维转化为一维:

           对于每个背包,以s为背包重量,t为背包价值,求出所有容量的包大小所能包含的价值。由于s有负值,所以加上100000;最后在背包容量大于等于0且价值大于等于0里面选择大和就好;


代码:

/****************************************************
* author:xiefubao
*******************************************************/
#pragma comment(linker, "/STACK:102400000,102400000")
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <stack>
#include <string.h>

using namespace std;

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


int dp[300000];
int n;
int inf=100000000;
int main()
{
  scanf("%d",&n);
  for(int i=0;i<300000;i++)
    dp[i]=-inf;
  dp[100000]=0;
  for(int i=0;i<n;i++)
  {
      int a,b;
      scanf("%d%d",&a,&b);
      if(a>=0)
      for(int j=100000;j>=-100000;j--)
      {
        if(dp[j+100000]>-inf)
          dp[j+a+100000]=max(dp[j+a+100000],dp[j+100000]+b);
      }
      else
      for(int j=-100000;j<=100000;j++)
      if(j+a+100000>=0&&dp[j+100000]>-inf)
          dp[j+a+100000]=max(dp[j+a+100000],dp[j+100000]+b);
  }
  int ans=0;
  for(int i=100000;i<=200000;i++)
  {
      if(dp[i]>0)
      ans=max(ans,dp[i]+i-100000);
  }
  cout<<ans<<endl;
   return 0;
}
/*
5
-5 7
8 -6
6 -3
2 1
-5 7
8 -6
6 -3
2 1
-8 -5
-8 -5
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值