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