与114.国王游戏 (https://www.acwing.com/problem/content/116/) 一样的思路,为了使风险值的最大值最小,应该将牛按照W+S从小到大的顺序从下往上排列。
C++ 代码
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> sums;
bool cmp(int a, int b)
{
return sums[a] < sums[b];
}
int main()
{
int N, W, S;
cin >> N;
vector<int> Ws(N), Ss(N), ranks(N);
sums.resize(N);
for (int i = 0; i < N; i++) {
cin >> W >> S;
Ws[i] = W;
Ss[i] = S;
sums[i] = W + S;
ranks[i] = i;
}
sort(ranks.begin(), ranks.end(), cmp);
int result = -1000000000;
int sum_W = 0;
for (int i = 0; i < N; i++) {
int cur_id = ranks[i];
result = max(result, sum_W - Ss[cur_id]);
sum_W += Ws[cur_id];
}
cout << result;
return 0;
}