Codeforces Round #723 (Div. 2)C2. Potions (Hard Version)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

原题链接: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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值