提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
原题链接:https://codeforces.com/problemset/problem/1526/C2
Description
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.
解题思路
只有小于 0 的数才可能让分数变为负数,那么就把每个负数放进一个小根堆的优先队列中,用一个sum统计从前往后统计从第一个到各个元素的和,每当 sum < 0 ,就删去队首元素,并将轮数减一,输出最后剩余的轮数即可。
AC代码
#include <iostream>
#include<algorithm>
#include<queue>
using namespace std;
int main(){
long long n,a,sum=0,len=0;
priority_queue<long long,vector<long long>,greater<long long>>q;
cin>>n;
int m=n;
while(n--){
cin>>a;
sum+=a;
if(a<0) q.push(a);
if(sum<0){
sum-=q.top();
q.pop();
m--;
}
}
cout<<m;
return 0;
}