题解:CF727F Polycarp's problems
link。
贪心做法。
本题贪心做法的实质就是用整数尽量多地抵消该整数后面的负数。
如果正着做,没有办法考虑全该数后面的所有负数,所以倒着做。
例如当前遍历到了
易得我们
但是剩下的
最终得到:
发现上述操作可以用堆来维护,具体维护方法见代码。
- 时间复杂度:
,瓶颈在于堆和二分。 - 空间复杂度:略。
代码:
// 加强版:n,m <= 1000000 代码
#include <bits/stdc++.h>
#define int long long
#define pii pair<int, int>
using namespace std;
const int N = 1e6 + 5;
int n, m, a[N], b[N], tot;
signed main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
priority_queue<int> q;
for (int i = n; i >= 1; i--) {
if (a[i] < 0) {
q.push(a[i]);
} else {
while (q.size() && a[i] >= 0) {
a[i] += q.top();
q.pop();
}
if (a[i] < 0) {
q.push(a[i]);
}
}
}
while (q.size()) {
b[++tot] = -q.top();
q.pop();
}
for (int i = 1; i <= tot; i++) {
b[i] += b[i - 1];
}
for (int i = 1; i <= m; i++) {
int x;
cin >> x;
if (x >= b[tot]) {
cout << "0\n";
continue;
}
int t = upper_bound(b + 1, b + tot, x) - b - 1;
cout << tot - t << "\n";
}
return 0;
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战