BZOJ 1629: [Usaco2007 Demo]Cow Acrobats

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 within 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.

题意:

有N头牛玩叠罗汉游戏,每头牛有一个体重Wi和一个力量Si。

这个游戏对每头牛都有一个危险度等于这头牛上面的牛的体重总和减去他的力量值。

求所有方案中危险值最大的最小。

题解:

显然对于相邻的两头牛A和B,调整A和B的顺序只能对A和B造成影响,对其它牛没有影响。

设都在A与B上面的牛的总体重的和是Sum。

当A在上B在下时,有max(A,B)=max(sum-S[a],sum+W[a]-S[b])

当A在下B在上时,有max(A,B)=max(sum+W[b]-S[a],sum-S[b])

那么如果A排在B的前面,就有max(sum-S[a],sum+W[a]-S[b])<max(sum+W[b]-S[a],sum-S[b])

两边都减去sum后直接扔快排比较函数里,排个序根据贪心就是最优的了。

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
//by zrt
//problem:
using namespace std;
typedef long long LL;
LL inf =(1<<30);
int n;
struct N{
    LL f,w;
    friend bool operator < (N a,N b){
        return max(a.w-b.f,-a.f)<max(-b.f,b.w-a.f);
    }
}a[50005];
int main(){
    #ifdef LOCAL
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
    #endif
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%lld%lld",&a[i].w,&a[i].f);
    }
    sort(a+1,a+1+n);
    LL ans=-inf;
    LL sum=0;
    for(int i=1;i<=n;i++){
        ans=max(ans,sum-a[i].f);
        sum+=a[i].w;
    }
    printf("%lld\n",ans);
    return 0;
}
posted @ 2014-09-09 22:55  zrt  阅读(220)  评论(0编辑  收藏  举报

Never stop,never ending!