POJ3045 Cow Acrobats
题意
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.
分析
考虑相邻的两头牛i和i+1,初始时他们的难受值是
交换后的难受值是
观察式子,发现需要比较的是
设前者小于后者,则
所以W和S的和大的牛排在下面更优。
时间复杂度\(O(N \log N)\)
代码
#include<iostream>
#include<algorithm>
#define rg register
#define il inline
#define co const
template<class T>il T read(){
rg T data=0,w=1;
rg char ch=getchar();
while(!isdigit(ch)){
if(ch=='-') w=-1;
ch=getchar();
}
while(isdigit(ch))
data=data*10+ch-'0',ch=getchar();
return data*w;
}
template<class T>il T read(rg T&x){
return x=read<T>();
}
typedef long long ll;
co int N=5e4+1;
int w[N],s[N],id[N];
bool cmp(int x,int y){
return w[x]+s[x]<w[y]+s[y];
}
int main(){
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
int n=read<int>();
for(int i=1;i<=n;++i)
read(w[i]),read(s[i]),id[i]=i;
std::sort(id+1,id+n+1,cmp);
int ans=0,sum=0;
for(int i=1;i<=n;++i)
ans=std::max(ans,sum-s[id[i]]),sum+=w[id[i]];
printf("%d\n",ans);
return 0;
}