acwing算法基础之贪心--排序不等式、绝对值不等式和推公式

123 篇文章 1 订阅

1 基础知识

暂无。。。

2 模板

暂无。。。

3 工程化

题目1:排队打水。给定N个数,表示装满每个桶所需的时间,请你安排打水顺序,使得等待时间最小,并输出该最小值。

解题思路:将所需时间小的桶排在前面。

C++代码如下,

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    int n;
    cin >> n;
    
    vector<int> nums;
    for (int i = 0; i < n; ++i) {
        int x;
        cin >> x;
        nums.emplace_back(x);
    }
    sort(nums.begin(), nums.end());
    
    long long res = 0;
    for (int i = 0; i < n; ++i) {
        res += nums[i] * (n - i - 1);
    }
    
    cout << res << endl;
    
    return 0;
}

题目2:货仓选址问题。给定N个数,求一个数x,使得这N个数减去x的绝对值之和最小,输出这个最小值。

解题思路:贪心做法。当n为奇数时,x取中位数;当n为偶数时,x取这两个中位数之间(包含这两个中位数)的任意一个数即可。

C++代码如下,

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

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

题目3:耍杂技的牛。有N头牛,它有重量和强壮值两个属性,将它们堆叠起来,某头牛的风险值等于其上所有牛的重量减去自身的强壮值。N头牛总共有N个风险值,有一个最大风险值。不同的排序方式,会有不同的最大风险值,求其最小值。

解题思路:按照重量和强壮值之和从小到大排序,这是最优的排序方式,会获得最小的最大风险值。

C++代码如下,

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main() {
    int n;
    cin >> n;
    
    vector<pair<int,int>> nums;
    for (int i = 0; i < n; ++i) {
        int w, s;
        cin >> w >> s;
        nums.emplace_back(w,s);
    }
    
    sort(nums.begin(), nums.end(), [](const pair<int,int> a, const pair<int,int> b) {
        return a.first + a.second < b.first + b.second;    
    });
    
    long long res = -2e9;
    long long sum = 0;
    for (auto [w, s] : nums) {
        res = max(res, sum - s);
        sum += w;
    }
    
    cout << res << endl;
    
    return 0;
}
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YMWM_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值