Notion of Heap
1.shape(查找方便
2
n
2n
2n and
2
n
+
1
2n+1
2n+1)
The binary tree is complete (except rightmost leaves)
2.The parent dominance(方便排序)
Make heap
Two methods:O(n)
- Bottom-top heap construction
- Top-down heap construction
Delete item
bottom-top heap construction O(log(n))
变式:vector只对v[i]做v[i-1]变换即可
void sink(int val){
while(2*val<=n){//最终是2*val
int i=2*val;
if(i+1<=n&&a[i+1]>a[i])i++;//易错点2
if(a[i]>a[val])swap(a[i],a[val]);
else return;
val=i;
}
}
void up(int val){//最终是val/2
while(val>1&&a[val>>1]<a[val]){
swap(a[val],a[val>>1]);
val>>=1;
}
}
int main(){
for(int i=n>>1;i>=1;--i)sink(i);//construct heap
while(--n){
swap(a[1],a[n+1]);
sink(1);
}
}