蓝桥杯真题 - 最大开支 - 题解

题目链接:https://www.lanqiao.cn/problems/3541/learning/

个人评价:难度 3 星(满星:5)

前置知识:贪心,结构体


整体思路

  • 根据题目名可知,虽然题目问的是"至少需要准备多少钱",但实际要求的是"最大开支",即所有人都按最贵的方式选择项目;
  • 由于参与项目的人数不同将决定项目的单价,不能直接按单价贪,考虑按增量贪心,即:如果第 i i i 个项目新加入一个成员,需要选择对答案增量最大的项目,这样才能使最终开支最大;
  • 首先计算在第 x x x 名成员加入第 i i i 个项目之前需要的开支 b e f o r e before before,即:

b e f o r e = { 0 x = 1 max ⁡ ( K i ( x − 1 ) + B i , 0 ) × ( x − 1 ) x ≠ 1 before= \begin{cases} 0 & x = 1 \\ \max(K_i (x - 1) + B_i, 0) \times (x - 1) & x \neq 1 \end{cases} before={0max(Ki(x−1)+Bi,0)×(x−1)x=1x=1

  • 其次计算第 x x x 名成员加入第 i i i 个项目之后需要的开支 a f t e r after after:

a f t e r = max ⁡ ( K i × x + B i , 0 ) × x after=\max(K_i \times x + B_i, 0) \times x after=max(Ki×x+Bi,0)×x

  • a f t e r − b e f o r e after-before after−before 就是第 x x x 个成员加入后的增量,每个成员贪心取最大的增量,使用优先队列维护即可。

过题代码

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;

typedef long long LL;
const int maxn = 100000 + 100;
struct Node {
    LL k, b, x, d;
    Node() {}
    
    // 计算增量 d
    Node(LL k, LL b, LL x) : k(k), b(b), x(x) {
        LL before = 0;
        if (x != 1) {
            before = max(k * (x - 1) + b, 0LL) * (x - 1);
        }
        d = max(k * x + b, 0LL) * x - before;
    }
};

bool operator<(const Node &a, const Node &b) {
    return a.d < b.d;
}

int n, m, k, b;
LL ans;
priority_queue<Node> que;

int main() {
#ifdef ExRoc
    freopen("test.txt", "r", stdin);
#endif // ExRoc
    ios::sync_with_stdio(false);

    cin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        cin >> k >> b;
        que.push(Node(k, b, 1));
    }
    for (int i = 1; i <= n; ++i) {
        Node tmp = que.top();
        que.pop();
        // 如果增量 <= 0,说明再取将会减少答案,此时让后面的人不再参与项目才能得到最大开支
        if (tmp.d <= 0) {
            break;
        }
        ans += tmp.d;
        tmp = Node(tmp.k, tmp.b, tmp.x + 1);
        que.push(tmp);
    }
    cout << ans << endl;

    return 0;
}
相关推荐
故事和你915 小时前
洛谷-数据结构1-1-线性表1
开发语言·数据结构·c++·算法·leetcode·动态规划·图论
脱氧核糖核酸__5 小时前
LeetCode热题100——53.最大子数组和(题解+答案+要点)
数据结构·c++·算法·leetcode
脱氧核糖核酸__5 小时前
LeetCode 热题100——42.接雨水(题目+题解+答案)
数据结构·c++·算法·leetcode
王老师青少年编程6 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:数列分段 Section I
c++·算法·编程·贪心·csp·信奥赛·线性扫描贪心
王老师青少年编程6 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:分糖果
c++·算法·贪心算法·csp·信奥赛·线性扫描贪心·分糖果
_日拱一卒6 小时前
LeetCode:2两数相加
算法·leetcode·职场和发展
py有趣6 小时前
力扣热门100题之零钱兑换
算法·leetcode
董董灿是个攻城狮7 小时前
Opus 4.7 来了,我并不建议你升级
算法
leaves falling7 小时前
C++模板进阶
开发语言·c++
无敌昊哥战神7 小时前
【保姆级题解】力扣17. 电话号码的字母组合 (回溯算法经典入门) | Python/C/C++多语言详解
c语言·c++·python·算法·leetcode