int heap[N];
int size=0;
void put(int x){//heap[1]為堆頂heap[++size]=x;//在堆尾加入元素int now=size;//當前結點序號while(now>1){int next=now>>1;//該結點的父結點if(heap[now]<=heap[next])//當前結點值小于其父結點值 break;swap(heap[now],heap[next]);now=next;}
}
2.get操作
get 操作,即從堆中取出并刪除堆頂元素,以小根堆為例,有:
令堆尾元素覆蓋掉堆頂元素,并將其作為根結點 father,同時將堆的長度 -1
如果 father 有子結點,將根結點的子結點中最小的那個置為當前子結點的 son;若 father 沒有子結點,結束操作
比較 father 與 son 的值,如果 father 的值小于或等于 son,結束操作;否則,交換這兩個結點,并把 father 指向 son,重復步驟 2,直至操作結束
int heap[N];
int get(){//heap[1]為堆頂int now=1;//當前結點int res=heap[1];要刪除的結點heap[1]=heap[size--];//堆長度-1while(now*2<=size){int next=now>>1;//當前結點的父結點if(next<size&&heap[next+1]<heap[next])//比較左右孩子,指向較大者next++;if(heap[now]<=heap[next])//當前結點值小于其父結點值,結束break;swap(heap[now],heap[next]);now=next;}return res;
}