题目描述
Farmer John's N (1 \leq N \leq 50,000)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.

输入描述:

  • 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_iand S_i.

输出描述:

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

思路
与国王游戏一样的思路,我们先分析每头牛的危险值 = 他前面牛的w(重量值)和 - 自身的s(强壮值),要使每头牛的危险值最小,这显然是与w 和 s同时相关。所以先按每头牛的w + s进行升序排序(题做多了都这样的题感)

牛 交换前 交换后
i −si wi+1−si
i+1 wi−si+1 −si+1
由于s, w都是正数,图片说明
比较图片说明 即可

图片说明 ,即 图片说明 时, 交换后更优

图片说明 ,即 图片说明 时, 交换前更优

完整C++版AC代码

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 500100;

typedef long long ll;
typedef pair<ll, ll> PII;

PII cows[N];
ll n;

int main() {
    ios::sync_with_stdio;
    cin >> n;
    for (int i = 0; i < n; i++) {
        ll w, s;
        cin >> w >> s;
        cows[i] = { w + s,w };
    }
    sort(cows, cows + n);
    ll res = -1e18, sum = 0;
    for (int i = 0; i < n; i++) {
        int s = cows[i].first - cows[i].second;
        res = max(res, sum - s);
        sum += cows[i].second;
    }
    cout << res << endl;
    return 0;
}