堆是什么?请点击
取出
取出加删除元素(小根堆)算法(简单粗略加通俗):
1.取出根结点。
2.最后一个节点将根结点覆盖,len--。
3.循环:把根结点和它儿子中小的一个交换,直到没有儿子。
硬模拟:
int get() { int now,next,res; res=heap[0]; heap[0]=heap[--len]; now=0; while(now*2<len) { next=now*2; if(next<len&&heap[next+1]<heap[next]) next++; if(heap[now]<=heap[next]) break; swap(heap[now],heap[next]); now=next; } return res; }以上代码编译过,未测试,呵呵,应该没问题。
当然,直接库函数,懒癌福利(需添加algorithm、iostream及using namespace std头文件):
int get() { //pop_heap(heap,heap+len);//大根堆 pop_heap(heap,heap+len,greater<int>());//小根堆 return heap[--len]; }
至于堆吧,排序是可以的,其实很容易发现,建立堆过后每次get出来的就是最小(大根堆就是最大)的。
以下是小根堆排序程序:
//小根堆排序 #include<cstdio> #include<iostream> #include<algorithm> using namespace std; int heap[100]; int n,len; void put(int k) { heap[len++]=k; push_heap(heap,heap+len,greater<int>()); } int get() { pop_heap(heap,heap+len,greater<int>()); return heap[--len]; } int main() { int x; scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d",&x); put(x); } for(int i=0;i<n;i++) printf("%d ",get()); return 0; }
By WZY