【bzoj2802】[Poi2012]Warehouse Store 贪心+堆

题目描述

有一家专卖一种商品的店,考虑连续的n天。
第i天上午会进货Ai件商品,中午的时候会有顾客需要购买Bi件商品,可以选择满足顾客的要求,或是无视掉他。
如果要满足顾客的需求,就必须要有足够的库存。问最多能够满足多少个顾客的需求。

输入

第一行一个正整数n (n<=250,000)。
第二行n个整数A1,A2,...An (0<=Ai<=10^9)。
第三行n个整数B1,B2,...Bn (0<=Bi<=10^9)。

输出

第一行一个正整数k,表示最多能满足k个顾客的需求。
第二行k个依次递增的正整数X1,X2,...,Xk,表示在第X1,X2,...,Xk天分别满足顾客的需求。

样例输入

6
2 2 1 2 1 0
1 2 2 3 4 4

样例输出

3
1 2 4


题解

贪心+堆

首先有个贪心策略:能卖就卖。

但是这样是有反例的,例如:第一天ai和bi相等且非常大,以后的ai=0,bi=1.

所以我们应该调整这个策略。

当无法满足时,此时无论如何调整也不能满足所有人,但是可以通过调整使得库存更多,即令前面满足的bi最大的变为不满足,然后满足当前的。

使用堆来维护,时间复杂度为$O(nlog n)$。

#include <queue>
#include <cstdio>
#include <utility>
#define N 250010
using namespace std;
typedef long long ll;
typedef pair<ll , int> pr;
priority_queue<pr> q;
ll a[N] , b[N];
bool tag[N];
int main()
{
	int n , i , ans = 0;
	ll now = 0;
	scanf("%d" , &n);
	for(i = 1 ; i <= n ; i ++ ) scanf("%lld" , &a[i]);
	for(i = 1 ; i <= n ; i ++ ) scanf("%lld" , &b[i]);
	for(i = 1 ; i <= n ; i ++ )
	{
		now += a[i];
		if(now >= b[i]) now -= b[i] , ans ++ , q.push(pr(b[i] , i));
		else if(!q.empty() && b[i] < q.top().first) now += q.top().first , q.pop() , now -= b[i] , q.push(pr(b[i] , i));
	}
	printf("%d
" , ans);
	while(!q.empty()) tag[q.top().second] = 1 , q.pop();
	for(i = 1 ; i <= n ; i ++ ) if(tag[i]) printf("%d " , i);
	printf("
");
	return 0;
}

 

原文地址:https://www.cnblogs.com/GXZlegend/p/7323785.html