forked from 18309220622/item
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeap.h
128 lines (115 loc) · 1.66 KB
/
Heap.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#pragma once
#include<iostream>
#include<assert.h>
#include<vector>
using namespace std;
template<class T>
struct Less
{
bool operator()(const T& l,const T& r)
{
return l<r;
}
};
template<class T>
struct Larger
{
bool operator()(const T& l,const T& r)
{
return l>r;
}
};
template<class T,class compare=Larger<T>>
class Heap
{
public:
Heap()
{}
Heap(T* a,size_t size)
{
assert(a);
_a.reserve(size);
for (size_t i=0;i<size;++i)
{
_a.push_back(a[i]);
}
//建堆,从第一个非叶子节点的父节点开始调整
for (int i=(size-2)/2;i>=0;--i)
{
AdjustDown(i);
}
}
void Push(const T& d)
{
_a.push_back(d);
AdjustUp(_a.size()-1);
}
void Pop()
{
assert(!_a.empty());
std::swap(_a[0],_a[_a.size()-1]);
_a.pop_back();
AdjustDown(0);
}
const T& Top()
{
assert(!_a.empty());
return _a[0];
}
bool Empty()
{
return _a.empty();
}
size_t Size()
{
return _a.size();
}
void Print()
{
for (size_t i=0;i<_a.size();++i)
{
cout<<_a[i]<<" ";
}
cout<<endl;
}
protected:
void AdjustDown(size_t root)
{
compare com;
size_t parent=root;
size_t child=parent*2+1; //先让child指向左孩子
while (child<_a.size())
{
//保证右孩子不为空,比较左右孩子
if (child+1<_a.size() && com(_a[child+1],_a[child]))
{
++child;
}
if (com(_a[child],_a[parent]))
{
std::swap(_a[parent],_a[child]);
parent=child;
child=parent*2+1;
}
else
break;
}
}
void AdjustUp(size_t child)
{
while (child>0)
{
compare com;
size_t parent=(child-1)/2;
if (com(_a[child],_a[parent]))
{
std::swap(_a[parent],_a[child]);
child=parent;
}
else
break;
}
}
protected:
vector<T> _a;
};