题解
2025-05-25 13:46:29
发布于:浙江
12阅读
0回复
0点赞
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
// 表示每个函数的结构体
struct Function {
int a, b, c;
// 计算函数在x处的值
int value(int x) const {
return a * x * x + b * x + c;
}
};
// 优先队列中的元素,包含函数索引和当前x值
struct Element {
int funcIdx; // 函数索引
int x; // 当前x值
int val; // 当前函数值
// 重载比较运算符,用于最小堆
bool operator>(const Element& other) const {
return val > other.val;
}
};
int main() {
int n, m;
cin >> n >> m;
vector<Function> functions(n);
for (int i = 0; i < n; i++) {
cin >> functions[i].a >> functions[i].b >> functions[i].c;
}
// 最小堆,使用greater比较器
priority_queue<Element, vector<Element>, greater<Element>> pq;
// 初始化每个函数的第一个元素(x=1)
for (int i = 0; i < n; i++) {
pq.push({i, 1, functions[i].value(1)});
}
// 输出前m个最小值
for (int i = 0; i < m; i++) {
Element current = pq.top();
pq.pop();
cout << current.val;
if (i < m - 1) cout << " ";
// 将该函数的下一个x值加入队列
int nextX = current.x + 1;
pq.push({current.funcIdx, nextX, functions[current.funcIdx].value(nextX)});
}
cout << endl;
return 0;
}
代码解释
Function 结构体:存储每个函数的系数 A、B、C,并提供计算函数值的方法
Element 结构体:表示优先队列中的元素,包含函数索引、当前 x 值和函数值
重载了比较运算符,使优先队列成为最小堆
主函数:
读取输入数据,初始化函数数组
初始化优先队列,将每个函数的第一个值(x=1 时)加入队列
循环 m 次,每次从队列中取出最小值并输出
将该函数的下一个值(x+1 时)加入队列
这种方法的时间复杂度为 O (m log n),其中 n 是函数数量,m 是需要输出的最小值数量。每次从堆中取出元素和插入新元素的操作都是 O (log n),共执行 m 次,因此效率较高,可以处理题目给定的数据范围。
这里空空如也
有帮助,赞一个