头文件:algorithm
函数:
make_heap()//建立堆 O(N)
push_heap()//在堆中添加数据 O(logN)
pop_heap()//在堆中删除数据 O(logN)
sort_heap()//堆排序 N*O(logN)
c++ 11 新加
is_heap()//判断给定区间是否是一个heap O(N)
is_heap_until//找出区间中第一个不满足heap条件的位置 O(N)
堆分为大顶堆(堆顶是最大值)和最小堆(堆顶是最小值),默认是大顶堆。
vector <int> a = {1,2,3,4,5,6};
make_heap(a.begin(), a.end());//默认
cout<<a[0]<<endl;//6
make_heap(a.begin(), a.end(), greater<int>());//小顶堆
cout<<a[0];//1
make_heap(a.begin(), a.end(),less<int>());//大顶堆
cout<<a[0]<<endl;
每一次向堆内传入新数据时要重新维护
vector <int> a = {1,2,3,4,5,6};
make_heap(a.begin(), a.end());//默认
cout<<a[0]<<endl;//6
a.push_back(7);
cout<<a[0]<<endl;//6
push_heap(a.begin(), a.end());//将新元素插入堆中
cout<<a[0]<<endl;//7
注意维护时要注意比较函数,如果是小顶堆
make_heap(a.begin(), a.end(), greater<int>());
cout<<a[0]<<endl;//1
a.push_back(-1);
cout<<a[0]<<endl;//1
push_heap(a.begin(), a.end(), greater<int>());
cout<<a[0]<<endl;//-1
也可以直接重新建堆,但注意建堆的复杂度是 o(n)
pop_heap():将堆头(最大值或最小值)放到堆尾,同时将其余元素调整成堆,注意处理前需确定当前区间已经是个堆
vector <int> a = {1,2,3,4,5,6};
make_heap(a.begin(), a.end());//默认
cout<<a[0]<<endl;//6
pop_heap(a.begin(), a.end());
cout<<a[0]<<endl;//5
cout<<a[5]<<endl;//6
a.pop_back();//用vector操作弹出最后的元素(6)
cout<<a.size();//5
sort_heap():对堆进行排序,每次选出当前堆的最大值(最小值)放在堆尾,再将剩余元素的最大值(最小值)放在堆尾-1,依次类推,直到所有元素有序,类似于执行n次pop_heap(),因此复杂度是n( log(n) ),注意处理前需确定当前区间已经是个堆
vector <int> a = {1,2,3,4,5,6};
make_heap(a.begin(), a.end(), greater<int>());//默认
sort_heap(a.begin(), a.end(), greater<int>());
for(int i=0; i<6; i++)
{
cout<<a[i]<<' ';//6 5 4 3 2 1
}
is_heap()及is_heap_until()
vector <int> a = {1,2,3,4,5,6};
cout<<is_heap(a.begin(), a.end())<<endl;//0
make_heap(a.begin(), a.end());
cout<<is_heap(a.begin(), a.end())<<endl;//1
a.push_back(7);
cout<<is_heap(a.begin(), a.end())<<endl;//0
for(int i=0; i<7; i++)
{
cout<<a[i]<<' ';
}
puts("");
auto iter = is_heap_until(a.begin(), a.end(), greater<int>());
cout<<*iter<<endl;//5