#include <iostream>
#include <vector>
using namespace std;
template<typename T> //仿函数,用来控制大堆小堆
struct Bigger
{
bool operator()(T left, T right)
{
return left > right;
}
};
template<typename T>
struct Lower
{
bool operator()(T left, T right)
{
return left < right;
}
};
template<typename T, typename Compare = Bigger<T>>
class Heap
{
public:
Heap(){}
Heap(T* a, size_t size)
:_a(a, a + size)
{
for (int i = (_a.size() - 2) / 2; i >= 0; --i)
{
_AdjustDown(i);
}
}
void Push(const T& x)
{
_a.push_back(x);
_AdjustUp(_a.size() - 1);
}
void Pop()
{
if (_a.size() == 0)
return;
swap(_a[0], _a[_a.size() - 1]);
_a.pop_back();
_AdjustDown(0);
}
protected:
void _AdjustDown(size_t index)
{
size_t parent = index;
size_t child = parent * 2 + 1;
while (child < _a.size())
{
if (child + 1<_a.size() && Compare()(_a[child + 1], _a[child]))
{
++child;
}
if (Compare()(_a[child], _a[parent]))
{
swap(_a[parent], _a[child]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
void _AdjustUp(size_t index)
{
size_t child = index;
size_t parent = (child - 1) / 2;
while (child > 0)
{
if (Compare()(_a[child], _a[parent]))
{
swap(_a[parent], _a[child]);
child = parent;
parent = (child - 1) / 2;
}
else
{
break;
}
}
}
protected:
vector<T> _a;
};
数据结构-堆(Heap)
最新推荐文章于 2024-11-05 17:16:24 发布