(DP - 01背包的变形)smrtfun

题目限制

时间限制内存限制评测方式题目来源
1000ms131072KiB标准比较器Local

题目背景

广东汕头聿怀初中 Train#2 Problem3

题目描述

 现有N个物品,第i个物品有两个属性A_i和B_i。在其中选取若干个物品,使得sum{A_i + B_i}最大,同时sum{A_i},sum{B_i}均非负(sum{}表示求和)。

输入格式

    第一行,一个整数,表示物品个数N。
    接下来N行,每行两个整数,表示A_i和B_i。

输出格式

一个整数,表示最大的sum{A_i + B_i}。

提示

 N <= 100 , |A_i| <= 1000 , |B_i| <= 1000

样例数据

输入样例 #1输出样例 #1
5
-5 7
8 -6
6 -3
2 1
-8 -5
8

 

题解:把 a[i] 看成体积,b[i]看成价值,就变成了 01背包,不过由于 a[i] 有负值,要将整体右移100000,这样,背包的最小容量为0,符合条件的最小容量为 100000,最大容量为 200000。

#include<set>
#include<map>
#include<list>
#include<queue>
#include<stack>
#include<math.h>
#include<vector>
#include<bitset>
#include<iomanip>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#define eps (1e-8)
#define MAX 0x3f3f3f3f
#define u_max 1844674407370955161
#define l_max 9223372036854775807
#define i_max 2147483647
#define re register
#define pushup() tree[rt]=(tree[rt<<1],tree[rt<<1|1]);
#define nth(k,n) nth_element(a,a+k,a+n);  // 将 第K大的放在k位
#define ko() for(int i=2;i<=n;i++) s=(s+k)%i // 约瑟夫
#define ok() v.erase(unique(v.begin(),v.end()),v.end()) // 排序,离散化
#define Catalan C(2n,n)-C(2n,n-1)  (1,2,5,14,42,132,429...) // 卡特兰数
using namespace std;

inline int read(){
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' & c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}

typedef long long ll;
const double pi = atan(1.)*4.;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3fLL;
const int M=63;
const int N=201005;
int dp[102][N];
int a[105],b[105];
int main(){
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d %d",&a[i],&b[i]);
    }

    for(int i=0;i<=n;i++)
        for(int j=0;j<=201004;j++) dp[i][j]=-999999;
    dp[0][100000]=0;
    for(int i=1;i<=n;i++){
        for(int j=200000;j>=0;j--){
            if(j>=a[i])
                 dp[i][j]=max(dp[i-1][j],dp[i-1][j-a[i]]+b[i]);
        }
    }
    int ans=-1;
    for(int i=100000;i<=200000;i++){
        if(dp[n][i]>=0)  ans=max(ans,dp[n][i]+i-100000);
    }
    printf("%d\n",ans);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值