P2085 最小函数值——小顶堆、贪心、重载运算符
题目描述
有
输入格式
第一行输入两个正整数
以下
输出格式
输出将这
输入输出样例 #1
输入 #1
3 10 4 5 3 3 4 5 1 7 1
输出 #1
9 12 12 19 25 29 31 44 45 54
说明/提示
数据规模与约定
对于全部的测试点,保证
题解
#include <iostream> #include <queue> #include <vector> using namespace std; // 定义结构体存储函数值、函数编号和当前 x 值 struct Node { int value; // 函数值 int funcIndex; // 函数编号 int x; // 当前 x 值 // 重载运算符,用于优先队列的比较 bool operator>(const Node& other) const { return value > other.value; } }; int main() { int n, m; cin >> n >> m; // 存储每个函数的 A, B, C 参数 vector<vector<int>> functions(n, vector<int>(3)); for (int i = 0; i < n; ++i) { cin >> functions[i][0] >> functions[i][1] >> functions[i][2]; } // 定义小根堆 priority_queue<Node, vector<Node>, greater<Node>> heap; // 初始化小根堆 for (int i = 0; i < n; ++i) { int A = functions[i][0]; int B = functions[i][1]; int C = functions[i][2]; // 计算 x = 1 时的函数值 int value = A * 1 * 1 + B * 1 + C; // 将 (函数值, 函数编号, 当前 x 值) 加入堆 heap.push({value, i, 1}); } // 存储结果 vector<int> result; // 进行 m 次操作 for (int i = 0; i < m; ++i) { // 取出堆中最小的函数值 Node top = heap.top(); heap.pop(); result.push_back(top.value); // 计算下一个 x 值对应的函数值 int A = functions[top.funcIndex][0]; int B = functions[top.funcIndex][1]; int C = functions[top.funcIndex][2]; int nextX = top.x + 1; int nextValue = A * nextX * nextX + B * nextX + C; // 将新的函数值加入堆 heap.push({nextValue, top.funcIndex, nextX}); } // 输出结果 for (int i = 0; i < m; ++i) { if (i > 0) { cout << " "; } cout << result[i]; } cout << endl; return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了