//******************************大堆****************************
template
<
typename
T
>
class
Heap
{
public
:
Heap()
{ }
Heap(
const
T
*
a
,
size_t
size
)
{
for
(
size_t
i = 0; i <
size
; ++i)
{
_a.push_back(
a
[i]);
}
for
(
int
i = (_a.size() - 2) / 2; i >= 0; --i)
{
_AdjustDown(i);
}
}
//向下调整,每次只调节一个父亲节点下面的所有分支
void
_AdjustDown(
int
parent
)
{
int
child =
parent
* 2 + 1;
while
(child < _a.size())
{
if
(child + 1 < _a.size() && _a[child + 1] > _a[child])
{
++child;
}
if
(_a[child]>_a[
parent
])
{
swap(_a[child], _a[
parent
]);
parent
= child;
child = 2 *
parent
+ 1;
}
else
break
;
}
}
//向上调整,每次向上调整一条线上的数据
void
_AdjustUp(
int
child
)
{
int
parent = (
child
- 1) / 2;
while
(
child
> 0)
{
if
(_a[parent] < _a[
child
])
{
swap(_a[parent], _a[
child
]);
child
= parent;
parent = (
child
- 1) / 2;
}
else
{
break
;
}
}
}
//插入一个数据到最小堆中
void
Push(
const
T
&
x
)
{
_a.push_back(
x
);
_AdjustUp(_a.size() - 1);
}
//删除堆顶元素
void
Pop()
{
assert
(_a.size() > 0);
swap(_a[0], _a[_a.size() - 1]);
_a.pop_back();
_AdjustDown(0);
}
T
& GetTop()
{
assert
(_a.size() > 0);
return
_a[0];
}
//判断是否为空
bool
Empty()
{
if
(_a.size() == 0)
{
return
true
;
}
return
false
;
}
size_t
Size()
{
return
_a.size();
}
void
Print()
{
for
(
int
i = 0; i < _a.size(); i++)
{
cout << _a[i] <<
" "
;
}
cout << endl;
}
private
:
vector
<
T
> _a;
};
//int main()
//{
// int array[10] = { 10, 16, 18, 12, 11, 13, 15, 17, 14, 19 };
// Heap<int> a1(array, sizeof(array) / sizeof(array[0]));
// /*a1.Print();
// a1.Push(20);
// a1.Print();
// a1._AdjustUp(a1.Size() - 1);
// a1.Print();
// a1.GetTop();
// a1.Size();*/
// return 0;
//}
//*************************优先级队列****************************
template
<
typename
T
>
class
PriorityQueue
{
public
:
void
Push(
const
T
&
x
)
{
hp.Push(
x
);
}
void
Pop()
{
hp.Pop();
}
private
:
Heap<
T
> hp;
};
int
main()
{
PriorityQueue
<
int
> que;
que.Push(1);
que.Push(5);
que.Push(3);
que.Push(7);
que.Push(6);
que.Push(9);
que.Pop();
que.Pop();
que.Pop();
return
0;
}