推公式——耍杂技的牛

由图可知,只要存在一个逆序,把他们交换一下,最大风险值就会降低,答案更优,因此最优解是按照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;
}
相关推荐
Дерек的学习记录1 小时前
C++:stack和queue
开发语言·c++·学习·算法
风中的微尘6 小时前
数学基础2
算法
一只小小的芙厨7 小时前
树状数组总结
数据结构·算法
郝学胜-神的一滴9 小时前
Effective STL 条款 17:用 swap 技巧去掉多余容量
c语言·开发语言·数据结构·c++·算法·rpc
玩转单片机与嵌入式9 小时前
深入浅出TinyML 36:如何验证一个TinyML系统真正具备工程应用价值?
网络·人工智能·算法
Nazarick11 小时前
力扣LeetCode热题75题(1)
java·算法·leetcode·力扣
16月6日-晴11 小时前
斐波那契数列题解
算法·leetcode
郝学胜-神的一滴12 小时前
Effective Python 条款47:吃透惰性属性
大数据·开发语言·数据库·人工智能·python·算法·oracle
Keven_1113 小时前
算法札记:有限差分
算法
忙里偷闲学python13 小时前
GK2A 林火蔓延预报算法说明
算法