POJ1456:Supermarket

浅谈堆:https://www.cnblogs.com/AKMer/p/10284629.html

题目传送门:http://poj.org/problem?id=1456

把物品按照时间排序,显然\(t\)天就只能卖\(t\)个物品。

所以我们把物品一个一个扔进堆里,当某天要卖的物品超过当前天数的时候一直把最小值从堆里弹出即可。

最后堆里剩下的元素就是要卖的元素。

时间复杂度:\(O(nlogn)\)

空间复杂度:\(O(n)\)

代码如下:

#include <cstdio>
#include <algorithm>
using namespace std;

const int maxn=1e4+5;

int n,ans;

int read() {
	int x=0,f=1;char ch=getchar();
	for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1;
	for(;ch>='0'&&ch<='9';ch=getchar())x=x*10+ch-'0';
	return x*f;
}

struct Com {
	int v,t;

	bool operator<(const Com &a)const {
		return t<a.t;
	}
}p[maxn];

struct Heap {
	int tot;
	int tree[maxn];

	void ins(int v) {
		tree[++tot]=v;
		int pos=tot;
		while(pos>1) {
			if(tree[pos]<tree[pos>>1])
				swap(tree[pos],tree[pos>>1]),pos>>=1;
			else break;
		}
	}

	int pop() {
		int res=tree[1];
		tree[1]=tree[tot--];
		int pos=1,son=2;
		while(son<=tot) {
			if(son<tot&&tree[son|1]<tree[son])son|=1;
			if(tree[son]<tree[pos])
				swap(tree[son],tree[pos]),pos=son,son=pos<<1;
			else break;
		}
		return res;
	}
}T;

int main() {
	while(~scanf("%d",&n)) {
		for(int i=1;i<=n;i++)
			p[i].v=read(),p[i].t=read();
		sort(p+1,p+n+1);ans=0;
		for(int i=1;i<=n;i++) {
			T.ins(p[i].v);
			while(T.tot>p[i].t)T.pop();
		}
		while(T.tot)ans+=T.pop();
		printf("%d\n",ans);
	}
	return 0;
}
posted @ 2019-01-18 14:46  AKMer  阅读(149)  评论(0编辑  收藏  举报