POJ3045 Cow Acrobats (贪心)

来源:互联网 发布:淘宝店铺入驻有什么好 编辑:程序博客网 时间:2024/04/27 17:48
Cow Acrobats
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 3207 Accepted: 1264

Description

Farmer John's N (1 <= N <= 50,000) cows (numbered 1..N) are planning to run away and join the circus. Their hoofed feet prevent them from tightrope walking and swinging from the trapeze (and their last attempt at firing a cow out of a cannon met with a dismal failure). Thus, they have decided to practice performing acrobatic stunts. 

The cows aren't terribly creative and have only come up with one acrobatic stunt: standing on top of each other to form a vertical stack of some height. The cows are trying to figure out the order in which they should arrange themselves ithin this stack. 

Each of the N cows has an associated weight (1 <= W_i <= 10,000) and strength (1 <= S_i <= 1,000,000,000). The risk of a cow collapsing is equal to the combined weight of all cows on top of her (not including her own weight, of course) minus her strength (so that a stronger cow has a lower risk). Your task is to determine an ordering of the cows that minimizes the greatest risk of collapse for any of the cows.

Input

* Line 1: A single line with the integer N. 

* Lines 2..N+1: Line i+1 describes cow i with two space-separated integers, W_i and S_i. 

Output

* Line 1: A single integer, giving the largest risk of all the cows in any optimal ordering that minimizes the risk.

Sample Input

310 32 53 3

Sample Output

2

Hint

OUTPUT DETAILS: 

Put the cow with weight 10 on the bottom. She will carry the other two cows, so the risk of her collapsing is 2+3-3=2. The other cows have lower risk of collapsing.

题目大意:n头牛,每头牛都有重量w和力量s,让n头牛从上到下叠一块,每头牛会有一个危险指数:sum(在这头牛上面的所有牛的重量w(不算它自己)) - 这头牛的力量s。

贪心,看着每头牛有两个属性w和s,都会影响到决策,庆幸的是,这两个属性对决策的影响是同向的,什么意思呢,就是w越大的就应该越靠下排,而s越大的也应该越靠下排,所以很简单,就按w+s排序就是正确的贪心策略。

不要去怀疑这个策略,可以用反正法证得,如果排序之后,你改变相邻的两头牛的顺序的话,其中有一头牛的系数减小的话,那另外一头牛的危险系数肯定要增大,得不偿失,所以不能交换,得证。

#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;typedef __int64 ll;const int maxn=50000+10;int n;struct pp{ll W,S;}s[maxn];int cmp(const pp &x,const pp &y){return x.S+x.W<y.S+y.W;}ll max(ll x,ll y){if(x>y) return x;return y;}int main(){ll i;while(scanf("%I64d",&n)!=EOF){for(i=0;i<n;i++){scanf("%I64d%I64d",&s[i].W,&s[i].S);}sort(s,s+n,cmp);ll res=-s[0].S,sum=0;for(i=0;i<n;i++){res=max(res,sum-s[i].S);sum+=s[i].W;}printf("%I64d\n",res);}return 0;}


0 0
原创粉丝点击