-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpriority_queue.cpp
More file actions
113 lines (93 loc) · 1.96 KB
/
priority_queue.cpp
File metadata and controls
113 lines (93 loc) · 1.96 KB
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
// priority_queue.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<vector>
#include<stdexcept>
#include<climits>
using namespace std;
class BinaryHeap
{
public:
explicit BinaryHeap(int capacity = 100);
explicit BinaryHeap(const vector<int> &items);
bool isEmpty() const;
const int& findMin() const;
void insert(const int &x);
void deleteMin();void deleteMin(int& minitem);
//void makeEmpty();
private:
int currentsize;
vector<int> array;
void builHeap();
void percolateDown(int hole);
};
BinaryHeap::BinaryHeap(int capacity) : currentsize(0)
{
array.resize(capacity);
array[0] = INT_MIN;
}
void BinaryHeap::builHeap()
{
for (int i = currentsize / 2; i > 0; --i)
percolateDown(i);
}
BinaryHeap::BinaryHeap(const vector<int> &items) : array(items.size() + 10), currentsize(items.size())
{
for (int i = 0; i < items.size(); ++i)
array[i + 1] = items[i];
builHeap();
}
void BinaryHeap::insert(const int &x)
{
if (currentsize == array.size() - 1)
array.resize(array.size() * 2);
int hole = ++currentsize;
for (; hole > 1 && x < array[hole / 2]; hole /= 2)
array[hole] = array[hole / 2];
array[hole] = x;
}
void BinaryHeap::deleteMin()
{
if (isEmpty())
throw new exception("underflow");
array[1] = array[currentsize--];
percolateDown(1);
}
void BinaryHeap::percolateDown(int hole)
{
int tmp = array[hole];
int child;
for (; hole * 2 <= currentsize; hole = child)
{
child = hole * 2;
if (child != currentsize && array[child + 1] < array[child])
++child;
if (array[child] < tmp)
array[hole] = array[child];
else
break;
}
array[hole] = tmp;
}
void BinaryHeap::deleteMin(int &x)
{
if (isEmpty())
throw new exception("underoverflow");
x = array[1];
array[1] = array[currentsize--];
percolateDown(1);
}
bool BinaryHeap::isEmpty() const
{
return currentsize < 1;
}
const int& BinaryHeap::findMin() const
{
if (isEmpty())
throw new exception("there is no extra data");
return array[1];
}
int main()
{
return 0;
}