题目描述
分析
假设一共有 5 5 5头牛, 且从上到下编号依次是 1 ∼ 5 1\sim5 1∼5
第 2 2 2头牛的风险值 = W 1 − S 2 = W_1 - S_2 =W1−S2 ①
第 3 3 3头牛的风险值 = W 1 + W 2 − S 3 = W_1 + W_2 - S_3 =W1+W2−S3 ②交换 2 , 3 2,3 2,3位置后, 从上到下依次是 1 , 3 , 2 , 4 , 5 1,3,2,4,5 1,3,2,4,5
第 2 2 2头牛的风险值 = W 1 + W 3 − S 2 = W_1 + W_3- S_2 =W1+W3−S2 ③
第 3 3 3头牛的风险值 = W 1 − S 3 = W_1 - S_3 =W1−S3 ④假设交换 2 , 3 2,3 2,3位置后,风险值较交换前更小
则需满足 m a x ( ① , ② ) > m a x ( ③ , ④ ) max(①,②) >max(③,④) max(①,②)>max(③,④)
即 m a x ( − S 2 , W 2 − S 3 ) > m a x ( − S 3 , W 3 − S 2 ) max(-S_2, W_2 - S_3)>max(- S_3,W_3- S_2) max(−S2,W2−S3)>max(−S3,W3−S2)
又因为 − S 2 < W 3 − S 2 , W 2 − S 3 > − S 3 -S_2 <W_3-S_2, W_2 -S_3 > -S_3 −S2<W3−S2,W2−S3>−S3,则需使 W 2 − S 3 > W 3 − S 2 W_2 - S_3 > W_3- S_2 W2−S3>W3−S2, 即 W 2 + S 2 > W 3 + S 3 W_2 +S_2 > W_3+S_3 W2+S2>W3+S3
经以上分析可知, 只要按 W + S W+S W+S升序排列, 风险值一定最小
注意求区间重量时,用前缀和优化一下
看不懂就参考Y总视频讲解
实现
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
typedef pair<int, int> PII;
const int N = 5e4 + 9;
const int INF = 0x3f3f3f3f;
int n;
PII p[N]; // w, s;
int sum[N]; // w的前缀和
int ans = -INF;
bool cmp(PII a, PII b)
{
return a.first + a.second < b.first + b.second;
}
int main()
{
cin >> n;
for(int i=1; i<=n; i++) cin >> p[i].first >> p[i].second;
sort(p+1, p+1+n, cmp);
for(int i=1; i<=n; i++) sum[i] = sum[i-1] + p[i].first;
for(int i=1; i<=n; i++) ans = max(ans, sum[i-1] - p[i].second);
cout << ans << endl;
return 0;
}