推公式——耍杂技的牛
由图可知,只要存在一个逆序,把他们交换一下,最大风险值就会降低,答案更优,因此最优解是按照wi+si从小到大升序排列,顺次计算每头牛的危险系数,最大值即是答案。
#include <iostream>
#include <algorithm>using namespace std;typedef pair<int, int> PII;const int N = 50010;int n;
PII cow[N];int main()
{cin>>n;for (int i = 0; i < n; i ++ ){int s, w;cin>>w>>s;cow[i] = {w + s, w};//pair是按照first为第一关键字排序,以second为第二关键字排序}sort(cow, cow + n);//升序int res = -2e9, sum = 0;//res代表风险值,sum当前这头牛上面所有牛的重量for (int i = 0; i < n; i ++ ){int s = cow[i].first - cow[i].second, w = cow[i].second;res = max(res, sum - s);sum += w;}cout<<res;return 0;
}