[板子]手写堆

 1 #include<bits/stdc++.h>
 2 #define N 100000
 3 using namespace std;
 4 struct Heap{
 5     int heap[N];
 6     int count;
 7     void push(int x){
 8         heap[++count]=x;
 9         int now=count;
10         while(now>1){
11             int nxt=now>>1;
12             if(heap[now]<heap[nxt])swap(heap[now],heap[nxt]);//
13             now=nxt;
14         }
15     }
16     int top(){return heap[1];}
17     void pop(){
18         int now=1;
19         heap[now]=heap[count--];
20         while((now<<1)<=count){
21             int nxt=(now<<1);
22             if((nxt|1)<=count&&heap[nxt|1]<heap[nxt])nxt++;//
23             if(heap[now]>heap[nxt])swap(heap[now],heap[nxt]);//
24             else break;
25             now=nxt;
26         }
27     }
28 }q;
29 int main(){//Accepted,手写小根堆,变成大根堆只需改上面
30     q.push(15);
31     q.push(2);
32     q.push(5);
33     q.push(8);
34     q.push(2);
35     q.push(9);
36     for(int i=1;i<=6;++i)printf("%d\n",q.top()),q.pop();
37 }

 

posted @ 2019-08-04 16:10  _xuefeng  阅读(56)  评论(0编辑  收藏  举报