Acwing算法基础课学习笔记(十八)--贪心之排序不等式&&绝对值不等式&&推公式

43 篇文章 2 订阅
10 篇文章 2 订阅
排队打水#include <iostream>#include <algorithm>using namespace std;const int N = 100010;int n;int t[N];int main(){ scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &t[i]); sort(t, t + n);
摘要由CSDN通过智能技术生成

排队打水
在这里插入图片描述

#include <iostream>
#include <algorithm>
using namespace std;

const int N = 100010;
int n;
int t[N];

int main()
{
      scanf("%d", &n);
      for (int i = 0; i < n; i++) scanf("%d", &t[i]);
      
      sort(t, t + n);
      
      long long res = 0;
      for (int i = 0; i < n; i++) res += t[i] * (n - 1 - i);
      
      printf("%lld\n", res);
      
      return 0;
}

货仓选址
在这里插入图片描述

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 100010;
int n;
int q[N];

int main()
{
    cin >> n;
    for (int i = 0; i < n; i++) cin >> q[i];
    
    sort(q, q + n);
    
    int res = 0;
    for (int i = 0; i < n; i++) res += abs(q[i] - q[n / 2]);
    
    cout << res << endl;
    return 0;
}

耍杂技的牛
国王游戏的贪心策略相似, 我们先分析每头牛的危险值 = 他前面牛的w(重量值)和 - 自身的s(强壮值),要使每头牛的危险值最小,这显然是与w 和 s同时相关。按每头牛的 w + s 进行排序, 当存在逆序时就进行交换(即升序排序),然后根据题意算出每头牛的危险值记录其中的最大值即可。

#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};
    }

    sort(cow, cow + n);

    int res = -2e9, sum = 0;
    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 << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值