二叉堆(插入,删除)

来源:互联网 发布:c语言产生随机数 编辑:程序博客网 时间:2024/06/05 20:55
#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;}

显然,堆是一种高效的数据结构
0 0
原创粉丝点击