解读题意
给定一个函数 $F_i(x)=A_ix^2+B_ix+C_i(x\in\mathbb{N}*)$ ,多次询问,分别给定 $A_i$、$B_i$、$C_i$,问这些函数的最小的 $m$ 个函数值
对于全部的测试点,保证 $1 \leq n,m\le10000$,$1 \leq A_i\le10$,$0 \leq B_i\le100$,$0 \leq C_i\le10^4$。
时间限制:$1.00s$ ;空间限制:$125MB$
思路
很明显的堆,关键的点在于堆的选择,是选择一个最小堆,等最后一次性的输出前 $m$ 个呢?
还是维护一个最大堆,每次将新增加的函数值和最大堆的堆顶元素进行比较,如果更小就 $pop$ 出堆顶,将元素加入堆呢?
显然是第二种,更省空间
总体难度:上位黄
还有一道类似题:P1631序列合并
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| #include <bits/stdc++.h> #define int long long #define endl '\n' using namespace std;
struct fx { int a, b, c; };
bool cmp(const fx &p, const fx &q) { if (p.a == q.a) { if (p.b == q.b) { return p.c < q.c; } return p.b < q.b; } return p.a < q.a; }
signed main() { ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); int n, m; cin >> n >> m; vector<fx> a(n); for (int i = 0; i < n; i++) { cin >> a[i].a >> a[i].b >> a[i].c; } sort(a.begin(), a.end(), cmp); priority_queue<int> pq; for (int i = 0; i < n; i++) { for (int j = 1; j <= m; j++) { int fx = a[i].a * j * j + a[i].b * j + a[i].c; if (static_cast<int>(pq.size()) < m) { pq.emplace(fx); } else if (pq.top() > fx) { pq.pop(); pq.emplace(fx); } } } vector<int> b; while (!pq.empty()) { b.push_back(pq.top()); pq.pop(); } sort(b.begin(), b.end()); for (int i = 0; i < m; i++) { cout << b[i] << " "; } cout << endl; return 0; }
|