堆模板

堆是一种简单高效的数据结构,在很多常用算法的优化上大显身手。

堆的常数很小,同样的数据,用堆来排序和快排的速度几乎相等,但是平衡树的速度会慢很多,Splay慢了两倍多。。

简单的学习一下堆,把模板发出来与大家分享


CODE(小根堆,排序):


#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MAX 200010
#define INF 0x7f7f7f7f
using namespace std;

struct SmallHeap{
	int num[MAX];
	int last;
	int Top() {
		return num[1];
	}
	void Insert(int x) {
		num[++last] = x;
		int now = last;
		while(num[now] < num[now >> 1] && now > 1)
			swap(num[now],num[now >> 1]),now >>= 1;
	}
	void Pop() {
		num[1] = num[last--];
		int now = 2;
		while(now <= last) {
			if(num[now] > num[now + 1])	++now;
			if(num[now] < num[now >> 1])	swap(num[now],num[now >> 1]),now <<= 1;
			else	break;
		}
	}
}heap;

int cnt;

int main()
{
	cin >> cnt;
	for(int x,i = 1;i <= cnt; ++i) {
		scanf("%d",&x);
		heap.Insert(x);
	}
	for(int i = 1;i <= cnt; ++i) {
		printf("%d\n",heap.Top());
		heap.Pop();
	}
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值