列表

详情


NC50958. Cow Acrobats

描述

Farmer John's   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 and strength. 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.

输入描述

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

输出描述

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

示例1

输入:

3
10 3
2 5
3 3

输出:

2

说明:

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.

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++14(g++5.4) 解法, 执行用时: 32ms, 内存消耗: 1772K, 提交时间: 2020-05-18 11:02:19

#include<bits/stdc++.h>
using namespace std;
const int N=5e4+10;
struct node
{
	int x,y;
}a[N];
int sum[N],mx,n;
bool cmp(node a,node b)
{
	return a.x+a.y<b.x+b.y;
}
int main()
{
	mx=INT_MIN;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	scanf("%d%d",&a[i].x,&a[i].y);
	sort(a+1,a+1+n,cmp);
	for(int i=1;i<=n;i++)
	sum[i]+=sum[i-1]+a[i].x;
	for(int i=1;i<=n;i++)
	mx=max(mx,sum[i-1]-a[i].y);
	printf("%d\n",mx);
	return 0;
}

C++ 解法, 执行用时: 32ms, 内存消耗: 716K, 提交时间: 2021-11-23 21:16:53

#include<bits/stdc++.h>
using namespace std;
struct node{int w,s;}a[100001];
int n,ans=INT_MIN,sum;
bool cmp(node x,node y){return x.w+x.s<y.w+y.s;}
int main(){
	cin>>n;
    for(int i=1;i<=n;i++)cin>>a[i].w>>a[i].s;
    sort(a+1,a+n+1,cmp);
    for(int i=1;i<=n;i++)ans=max(ans,sum-a[i].s),sum+=a[i].w;
    cout<<ans;
    return 0;
}

上一题