题目链接
题目描述:
Cow Exhibition
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 12055 Accepted: 4792
Description
“Fat and docile, big and dumb, they look so stupid, they aren’t much
fun…”
- Cows with Guns by Dana Lyons
The cows want to prove to the public that they are both smart and fun. In order to do this, Bessie has organized an exhibition that will be put on by the cows. She has given each of the N (1 <= N <= 100) cows a thorough interview and determined two values for each cow: the smartness Si (-1000 <= Si <= 1000) of the cow and the funness Fi (-1000 <= Fi <= 1000) of the cow.
Bessie must choose which cows she wants to bring to her exhibition. She believes that the total smartness TS of the group is the sum of the Si’s and, likewise, the total funness TF of the group is the sum of the Fi’s. Bessie wants to maximize the sum of TS and TF, but she also wants both of these values to be non-negative (since she must also show that the cows are well-rounded; a negative TS or TF would ruin this). Help Bessie maximize the sum of TS and TF without letting either of these values become negative.
Input
Line 1: A single integer N, the number of cows
Lines 2..N+1: Two space-separated integers Si and Fi, respectively the smartness and funness for each cow.
OutputLine 1: One integer: the optimal sum of TS and TF such that both TS and TF are non-negative. If no subset of the cows has non-negative TS and non- negative TF, print 0.
Sample Input
5
-5 7
8 -6
6 -3
2 1
-8 -5
Sample Output
8
Hint
OUTPUT DETAILS:
Bessie chooses cows 1, 3, and 4, giving values of TS = -5+6+2 = 3 and TF
= 7-3+1 = 5, so 3+5 = 8. Note that adding cow 2 would improve the value
of TS+TF to 10, but the new value of TF would be negative, so it is not
allowed.
题意:
给出n(n<=100)头奶牛的S和F值(-1000<=S,F<=1000),要求在这几头奶牛中选出若干头,使得在其总S值TS和总F值TF均不为负的前提下,求TS+TF的最大值。
分析:
好题,可以固定一维求另一维度最大值,然后遍历一遍求总和最大值,可以把S当体积,F当价值做01背包。但是S可为负,所以整体加100000,然后要注意更新,S为负是要顺向更新,为正时逆向更新。
而且此处体积的变化范围为0-200000.
ac代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=100000;
const int Maxn=100+5;
const int inf=0x3f3f3f3f;
int d[maxn*2+10];
int s[Maxn],f[Maxn];
int main()
{
//freopen("in.txt","r",stdin);
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d%d",&s[i],&f[i]);
for(int i=0;i<=maxn*2;i++)//进行初始化,与往常的0-1背包初始化不同,往常0-1背包d[i]指的是不超过体积i的最大重量,
d[i]=-inf; //故只需要全部初始化为0,此处的d[i]表示的是体积为i时的最大重量,将d[maxn]赋值为0,
d[maxn]=0; //将其他赋值为-inf是为了使得递推从d[maxn]开始,以符合逻辑
for(int i=1;i<=n;i++)
{
if(s[i]>=0)
{
for(int j=2*maxn;j>=s[i];j--) //逆向更新,注意体积范围!
d[j]=max(d[j],d[j-s[i]]+f[i]);
}
else
{
for(int j=0;j<=2*maxn+s[i];j++) //顺向更新 ,注意体积范围!
d[j]=max(d[j],d[j-s[i]]+f[i]);
}
}
int ans=0;
for(int i=maxn;i<=2*maxn;i++)
if(d[i]>0)
ans=max(ans,i-maxn+d[i]);
printf("%d\n",ans);
}