动态规划

POJ2184总结

Cow Exhibition

题目来源

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.

Output

* Line 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.

我的代码

每一只牛只可以选0次或者1次,所以是典型的01背包问题,应当将Fi或者Si作为容量处理,另一个作为价值。这一题较难处理的是容量和价值都有负数的情况,这就导致了两个问题:一是容量为负的情况下,dp数组要怎么开?二是价值为负的情况下,初始化为什么值?

对于容量为负的情况,可以将坐标轴向右移动N*MAX_Si;对于价值为负的情况,直接全都初始化为0是行不通的,因为这一道题目中,其实背包的容量是可变的,且当背包容量确定之后,这个背包实际上就已经被装满了,然而背包的容量并不一定能达到理想情况的最大值,这就导致如果直接赋值为0,计算得到的结果是实际上达不到的,因此初始化时需要全部赋值为无穷小,且当背包的实际容量(平移后的)赋值为0。

对于容量为负数的情况,还有一个要特别注意的是,遍历的方向。在普通的01背包中,所有物品的大小都是正数,压缩完空间后需要逆序遍历。在此题中有大小为负数的情况,这是就需要从逆序的反方向,即正序遍历了。

#include<stdio.h>
#include<algorithm>

using namespace std;

int dp[200010];
int smart[105],fun[105];
int main()
{
	int n=0,ans=0;
	scanf("%d",&n);
	for (int i=0;i<n;i++){
		scanf("%d%d",&smart[i],&fun[i]);
	}
	for (int i=0;i<=200000;i++){
		dp[i]=-100000;
	}
	dp[100000]=0;
	for (int i=0;i<n;i++){
		if (smart[i]<=0&&fun[i]<=0) continue;
		if (smart[i]>0){
			for (int j=200000;j>=smart[i];j--){
				dp[j]=max(dp[j],dp[j-smart[i]]+fun[i]);
			}
		}else{
			for (int j=0;j<=200000+smart[i];j++){
				dp[j]=max(dp[j],dp[j-smart[i]]+fun[i]);
			}
		}
	}
	for (int i=100000;i<=200000;i++){
		if (dp[i]>=0){
			ans=max(ans,dp[i]+i-100000);
		}
	}
	printf("%d\n",ans);
	return 0;
}