二叉堆(插入,删除)

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
using namespace std;
int heap[100000],len;
void up(){
	int k=len;
	while(k>1){
		if(heap[k]<heap[k>>1])swap(heap[k],heap[k>>1]);
		k>>=1;
	}
}
void down(int n){
	while(n<<1<=len){
		if(heap[n<<1]<heap[n<<1|1]){
			if(heap[n<<1]<heap[n])
			swap(heap[n<<1],heap[n]);
		}
		else if(heap[n<<1|1]<heap[n<<1]){
			if(heap[n<<1|1]<heap[n])
			swap(heap[n<<1|1],heap[n]);
		}
	}
}
void pop(int n){
	heap[1]=heap[len];
	len--;
	down(1);
}
void push(int n){
	heap[++len]=n;
	up();
}
int main(){
	int i,j,k,m,n,x;
	scanf("%d",&n);
	while(n--){
		scanf("%d",&x);
		push(x);
	}
	for(i=1;i<=len;i++)printf("%d ",heap[i]);
	return 0;
}

显然,堆是一种高效的数据结构
posted @ 2016-12-24 11:16  Drinkwater_cnyali  阅读(572)  评论(0编辑  收藏  举报