Potions (Hard Version)
This is the hard version of the problem. The only difference is that in this version n≤200000
. You can make hacks only if both versions of the problem are solved.
There are n
potions in a line, with potion 1 on the far left and potion n on the far right. Each potion will increase your health by ai when drunk. ai
can be negative, meaning that potion will decrease will health.
You start with 0
health and you will walk from left to right, from first potion to the last one. At each potion, you may choose to drink it or ignore it. You must ensure that your health is always non-negative.
What is the largest number of potions you can drink?
Input
The first line contains a single integer n
(1≤n≤200000
) — the number of potions.
The next line contains n
integers a1, a2, … ,an (−109≤ai≤109
) which represent the change in health after drinking that potion.
Output
Output a single integer, the maximum number of potions you can drink without your health becoming negative.
翻译:
这是问题的硬版本。唯一的区别是在这个版本中≤20万。只有两个版本的问题都解决了,你才能进行黑客攻击。
一行有n种药剂,药剂1在最左边,药剂n在最右边。每一种药剂都会增加你的生命值。ai可以是负的,意味着药剂会降低生命值。
你从0点生命值开始,从左到右,从第一个魔药到最后一个魔药。在每一个药水,你可以选择喝它或忽略它。你必须确保你的健康永远是非负的。
你能喝的药水最多是多少?
(原文链接:https://blog.csdn.net/lalala625/article/details/117380261)
题解:
标准的反悔贪心 用优先队列存一下就ok了
#include<iostream>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<string>
const int N = 2e5 + 10;
using namespace std;
int a[N];
int main(void) {
long long n, x;
cin >> n;
priority_queue<long long, vector<long long>, greater<long long> > q;
long long sum = 0, cnt = 0;
for (int i = 1; i <= n; i++) {
cin >> x;
if (x >= 0) {
sum += x;
cnt++;
} else {
if (sum + x >= 0) {
sum += x;
cnt++;
q.push(x);
} else {
if (q.empty())continue;
else if (x > q.top()) {
sum -= q.top();
sum += x;
q.pop();
q.push(x);
}
}
}
}
cout << cnt << endl;
return 0;
}