原版推导证明过程见:大佬博客
题目中,因风险值
= = =前 i − 1 i-1 i−1头牛的总重量 ∑ j = 0 j = i − 1 W i − \sum_{j=0} ^{j=i-1} W_i - ∑j=0j=i−1Wi− 第 i i i头牛的强壮值 S i S_i Si(两个因素共同决定)
。
所以,以组合W+S的方式,来对每头牛的{W+S,W}进行排序(先第一个关键字,再第二个关键字)
结论: w i + s i < = w i + 1 + s i + 1 w_i + s_i <= w_{i + 1} + s_{i + 1} wi+si<=wi+1+si+1
#include <iostream>
#include <cstring>
#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;
typedef pair<int,int> pii;
const int N = 1e5 + 10;
int n;
pii a[N];
int main(){
scanf("%d",&n);
for(int i = 0; i < n; i++){
int w,s;
scanf("%d%d",&w,&s);
a[i] = {w + s, w};
}
sort(a,a + n);
int res = -1e9;
for(int i = 0, sum = 0; i < n; i++){
int w = a[i].y, s = a[i].x - w;
res = max(res,sum - s);//sum为前i-1头牛的总重
sum += w;
}
printf("%d\n",res);
return 0;
}