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
3 10 3 2 5 3 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.
题意:
一群牛在叠罗汉; 每头牛都有一个重量W和力量值X; 在叠的时候每头牛都有一个风险值R; 要你求总的风险值中最大的那个风险值R’
思路:想了很长时间,根本无从下手,然后就对各位大佬的思路下手了,在这里有两种方法来解决这个叠罗汉问题,第一种比较好写一些;
在这里需运用贪心的方法来解决,我们可以将每一只牛的W+H加起来,然后从小到大的顺序sort一下,然后按照将求和得到的值大的放到下面,再继续枚举每一只牛的危险值(可能为负数,因此要注意开始设置一个无穷小量),最终找到里面最大的值,就是答案了;
为什么上面的思路求解的是对的,那就需要数学证明一下:
假设当前的A,B两只牛的的顺序就是所需的最优的顺序,并且说明A在B的上面,定义一个sum代表A上面的牛的总重量,那么:
DangerA=sum-A.s;DangerB=sum+A.w-B.s;
其中两者的危险值都是最优的,然后将A,B两只牛的顺序变一下,那么此时的sum的值是不变的,因此:
DangerA'=sum+B.w-A.s;DangerB'=sum-B.s;
由于假设A在上的情况是最优的,那么此时交换后B位置的危险值为DangerA',那么DangeA’>=DangerB';
即sum+B.w-A.s>=sum+A.w-B.s ==> B.s+B.w>=A.s+A.w;那么最优的放置方案应该是两者之和大的放在下面,有次思路便能够AC;
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include<set>
using namespace std;
typedef long long ll;
#define rep(i,l,r) for(int i=l;i<=r;i++)
#define lep(i,l,r) for(int i=l;i>=r;i--)
const ll INF=(ll)1<<63;
const int N=1e6+400;
int n;
struct node
{
ll s,w,sum;
bool operator < (const node &a) const{
return sum<a.sum;
}
}a[50009];
int main(){
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif // ONLINE_JUDGE
scanf("%d",&n);
rep(i,1,n)
scanf("%lld%lld",&a[i].w,&a[i].s),a[i].sum=a[i].s+a[i].w;
sort(a+1,a+n+1);
ll ans=-INF;
ll tot=0;
rep(i,1,n){//当n为1的时候,输出的结果是-a[1].s;
tot-=a[i].s;
ans=max(ans,tot);
tot=tot+a[i].w+a[i].s;
}
printf("%lld\n",ans);
return 0;
}