蓝桥杯(C++ 最大开支 优先队列)

优先队列: 蓝桥杯(C++ 整数删除 优先队列 )-CSDN博客

思路:

1、每个人依此选择项目,每个人选项目时都(选择当下花费增加最多的项目),若项目i的门票价格为kx+b,那么增加一个人选择的花费为:increase =(k*(x+1)+b)*(x+1)- ((k*x)+b)*x x = k(2x+1) + b

2、可以用优先队列存项目的k、b、x(选择这个项目的人数)、increase(当前项目人数增加为x+1所增加的花费),使increase最大的项目排在队首,每加一个人出队一个并使总花费增加increase,即总花费money = money + increase

3、更新x和increase,若increase > 0重新入队,若increase <= 0不重新入队(人数到了开口向下的二次函数的对称轴,花费开始下降,不能再增加人数了

代码:

cpp 复制代码
#include<iostream>
#include<queue>
#include<functional>
using namespace std;
using ll = long long;
struct node
{
    int k, b, x , increase;
};
bool operator < (const struct node a, const struct node b)//重载<
{
    return a.increase < b.increase;
}
int main()
{
    int n, m;
    cin >> n >> m;
    priority_queue<node>h;//大根堆
    node a;
    for (int i = 0; i < m; i++)
    {
        cin >> a.k >> a.b;
        a.increase = a.k + a.b;
        if (a.increase <= 0)//小于等于零的不入队
            continue;
        a.x = 1;
        h.push(a);
    }
    ll money = 0, person;
    for (person = 0; !h.empty() && person < n; person++)
    {
        if (h.top().increase > 0)//防止第一个就小于零
        {
            node temp = h.top();
            h.pop();
            money += temp.increase;//加上增加的花费
            //increase=(k*(x+1)+b)*(x+1)-((k*x)+b)*x 再增加一个人会不会比之前花费更多
            temp.increase = temp.k * (2 * temp.x + 1) + temp.b;
            if (temp.increase > 0)//比之前还更多,重新入队
            {
                temp.x += 1;
                h.push(temp);
            }
        }
        else
            break;
    }
    cout << money;
}
相关推荐
_F_y3 小时前
MySQL用C/C++连接
c语言·c++·mysql
兩尛3 小时前
c++知识点2
开发语言·c++
fengfuyao9853 小时前
海浪PM谱及波形的Matlab仿真实现
开发语言·matlab
xiaoye-duck3 小时前
C++ string 底层原理深度解析 + 模拟实现(下)——面试 / 开发都适用
开发语言·c++·stl
Azure_withyou4 小时前
Visual Studio中try catch()还未执行,throw后便报错
c++·visual studio
琉染云月4 小时前
【C++入门练习软件推荐】Visual Studio下载与安装(以Visual Studio2026为例)
c++·visual studio
Hx_Ma164 小时前
SpringMVC框架提供的转发和重定向
java·开发语言·servlet
期待のcode5 小时前
原子操作类LongAdder
java·开发语言
L_09075 小时前
【C++】高阶数据结构 -- 红黑树
数据结构·c++
A_nanda5 小时前
c# MOdbus rto读写串口,如何不相互影响
算法·c#·多线程