Potions (Hard Version)

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值