CF #723 (Div. 2)C1_C2. Potions (Hard Version)可反悔贪心
Posted 小哈里
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CF #723 (Div. 2)C1_C2. Potions (Hard Version)可反悔贪心相关的知识,希望对你有一定的参考价值。
problem
C2. Potions (Hard Version)
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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.
Example
inputCopy
6
4 -4 1 -3 1 -3
outputCopy
5
Note
For the sample, you can drink 5 potions by taking potions 1, 3, 4, 5 and 6. It is not possible to drink all 6 potions because your health will go negative at some point
solution
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int main(){
ios::sync_with_stdio(false);
LL n, x; cin>>n;
priority_queue<LL, vector<LL>, greater<LL> >q;
LL 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;
if(x>q.top()){
sum -= q.top();
sum += x;
q.pop();
q.push(x);
}
}
}
}
cout<<cnt<<"\\n";
return 0;
}
以上是关于CF #723 (Div. 2)C1_C2. Potions (Hard Version)可反悔贪心的主要内容,如果未能解决你的问题,请参考以下文章
Codeforces Round #723 (Div. 2)
Codeforces Round #723 (Div. 2)
Codeforces Round #723 (Div. 2), A. Mean Inequality