推公式——耍杂技的牛

由图可知,只要存在一个逆序,把他们交换一下,最大风险值就会降低,答案更优,因此最优解是按照wi+si从小到大升序排列,顺次计算每头牛的危险系数,最大值即是答案。

cpp 复制代码
#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;
}
相关推荐
Zane19941 分钟前
暴力字符串匹配失配就要把文本指针往回拉,KMP凭什么能让它一直往前走
算法
Tim_1033 分钟前
【LeetCode】338、比特位计数
c++·算法·leetcode
木子算法1 小时前
不是重心也不是中点:费马—韦伯点、它的最优性条件与迭代求解
人工智能·算法·目标跟踪
tryxr2 小时前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_32 小时前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Selvaggia2 小时前
DMD(Distribution Matching Distillation,分布匹配蒸馏)
算法
Navigator_Z2 小时前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.2 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.3 小时前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
wzdark3 小时前
数据压缩算法的时间复杂度与压缩率权衡4
算法