Codeforces Round #723 (Div. 2)C2. Potions (Hard Version)[贪心+优先队列]

Codeforces Round #723 (Div. 2)C2. Potions (Hard Version)[贪心+优先队列]

题目大意

一共有 n (n<=200000) 瓶药剂,每一瓶药剂既可以喝也可以不喝,初始生命值为sum=0,每喝一种药剂 生命值变为 sum+= a i a_i ai,要求喝尽可能的多的药剂,但必须保证生命值时刻非负。

思路:

  • 假设当前到了第 i i i 瓶药剂,并且前 i − 1 i-1 i1 已经选择了最优方案,被选中的药剂集合 q i − 1 q_{i-1} qi1,此时我们直接喝下第 i i i 瓶药剂,然后判断生命值是否非负,如果为负数,则逐渐删除 q i q_{i} qi中最小的元素 ,直到生命值非负。确实就是反悔加贪心

    • 证:每删除 q i q_{i} qi 中的一个最小元素 y y y 付出 1 的代价,收获的确是最多的,并且因为是这样转移的,所以前面每一个 q x q_{x} qx 都是合法的,他们在删除 y y y 后仍然合法。
  • 上述 q i q_i qi 可采用优先队列,总复杂度O(nlogn)。

input:

6
4 -4 1 -3 1 -3

output:

5

code:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<queue>
#include<vector>
#include<map>
#include<set>
using namespace std;
#define Please return 
#define Accepted 0
#define int long long
#define endl "\n"
typedef long long LL;
typedef pair<int,int> PII;
typedef pair<double, double> PDD;
const int N = 200010,M=2*N,INF=0x3f3f3f3f;
int n;
int a[N];
void slove(int _case)
{
	cin>>n;
	int sum=0,ans=0;
	priority_queue<int,vector<int>,greater<int>  > q;
	for(int i=1;i<=n;i++){
		cin>>a[i];
		sum+=a[i];q.push(a[i]);
		while(!q.empty()&&sum<0){
//			cout<<q.top()<<endl;
			sum-=q.top();q.pop();
		}
		ans=max(ans,(int)q.size());
	}
	cout<<ans<<endl;
}

signed main()
{
	ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	int T=1;
//	cin>>T;
	for(int _case=1;_case<=T;_case++)
	{
		slove(_case);
	}
	Please Accepted;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值