堆——学习笔记

堆——学习笔记

完全二叉树形式

具有单调性

可以用来求最值

也可以用来求最值

分类

大根堆:根节点最大

小根堆:根节点最小

STL_heap

借助vector来建堆

初始化

#include<bits/stdc++.h>
using namespace std;
int main(){
   int n;
   vector<int> a;
   for(int i=1;i<=n;i++){
int num;
       cin>>num;
       a.push_back(num);
  }
   return 0;
}

建堆


make_heap(a.begin(),a.end(),cmp);

bool cmp(int a,int b){
return x>y;//小根堆
}

推入元素


a.push_back(num);
make_heap(a.begin(),a.end(),cmp);//起维护堆的作用

删除元素


pop_heap(a.begin(),a.end(),cmp);//把第一个元素放到最后
a.pop_back();//删除最后一个元素

手写

以小根堆为例

上浮——shift_up


void shift_up(int i){
   while(i/2>=1){
if(heap[i]<heap[i/2]){//大根堆要换
swap(heap[i],heap[i/2]);
           i=i/2;
      }else{
break;
      }
  }
   return 0;
}

下沉——shift_down


void shift_down(int i,int n){//n个节点
while(i*2<=n){
       int t=i*2;
       if(t+1<=n&&heap[t+1]<heap[t]){
t=t+1;
      }
       if(heap[i]>heap[t]){
swap(heap[i],heap[t]);
           i=t;
      }else{
           break;
      }
  }
   return 0;
}

插入——push


void push(int a,int n){
n++;
   heap[n]=a;
   shift_up(n);
   return 0;
}

弹出——pop


void pop(){
   swap(heap[1],heap[n]);
   n--;
   shift_down(1);
   return 0;
}

取顶——top


int top(){
   if(n>0){
return a[1];
  }else{
return 0;
  }
}

堆排序——heap_sort

把数据一个一个推入堆里,开一个新数组,挨个弹出


void heap_sort(){//省略推入部分
k=0;
   while(n>0){
k++;
       a[k]=top();
       pop();
  }
}

wsy:

P3378 【模板】堆

P1090 合并果子

hzwer:

[Usaco2006 Nov] Fence Repair 切割木板

luan:

P1631 序列合并

P1168 中位数

posted @ 2021-01-27 16:41  wsy_jim  阅读(75)  评论(0编辑  收藏  举报