[POJ 2184]--Cow Exhibition(0-1背包变形)

题目链接:http://poj.org/problem?id=2184

Cow Exhibition
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 9479   Accepted: 3653

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

题目大意:
    N头奶牛中(N大于0且N小于100) 选择一部分去参加一个展览。 每头奶牛有两个指标,Si和Fi(-1000<=Si,Fi<=1000),
    分别代表每头奶牛的聪明指数和快乐指数。求所挑选奶牛的Si和Fi的总和最大值,且Si和Fi各自的和数不能小于0。

解题思路:怎么说呐~~此题略坑,也是看了不少博客a出来的,巧妙的运用dp,吧si的正负影响转移了,
     然后0-1背包的思路来做按,依照si正负按照正反两个方向dp,然后在满足条件的情况下,
     然后你会发现最后i的增量就是满足条件的si的和,然后遍历dp数组筛选即可~~(具体的看看代码吧)

代码如下:
 1 #include<iostream>
 2 #include<cstring>
 3 using namespace std;
 4 const int inf = 0x3f3f3f3f;
 5 const int maxn = 100000;
 6 const int add = 100000;
 7 int dp[200001], si, fi, n, i, j, ans;
 8 int main()
 9 {
10     cin >> n;
11     memset(dp, -inf, sizeof(dp));
12     dp[add] = 0;
13     for (i = 1; i <= n; i++)
14     {
15         cin >> si >> fi;
16         if (si > 0)
17         {
18             for (j = maxn + add; j >= si; j--)
19             if (dp[j - si] + fi > dp[j] && dp[j - si] > -inf)//注意边界判断
20                 dp[j] = dp[j - si] + fi;
21         }
22         else
23         {
24             for (j = 0; j <= maxn + add + si; j++)
25             if (dp[j - si] + fi > dp[j] && dp[j - si] > -inf) 
26                 dp[j] = dp[j - si] + fi;
27         }
28     }
29     for (i = add; i <= maxn + add; i++)
30     if (dp[i] >= 0 && i + dp[i] - add > ans)
31         ans = i + dp[i] - add;
32     cout << ans << endl;
33     return 0;
34 }
View Code


原文地址:https://www.cnblogs.com/zyxStar/p/4574847.html