-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2022-06-16.cpp
More file actions
67 lines (59 loc) · 995 Bytes
/
2022-06-16.cpp
File metadata and controls
67 lines (59 loc) · 995 Bytes
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
#include <iostream>
#include <vector>
using namespace std;
class PriorithyQueue
{
private:
vector<int> m_heap;
public:
int top()
{
return m_heap[0];
}
bool empty()
{
return m_heap.empty();
}
void push(int data)
{
m_heap.push_back(data);
int now = m_heap.size() - 1;
while (now > 0)
{
int next = (now - 1) / 2;
if (m_heap[now] < m_heap[next]) break;
swap(m_heap[now], m_heap[next]);
now = next;
}
}
void pop()
{
m_heap[0] = m_heap.back();
m_heap.pop_back();
int parent = 0;
int child = 1;
while (child <= (int)m_heap.size() - 1) {
if(child < m_heap.size() - 1)
if(m_heap[child] < m_heap[child + 1])
++child;
if (m_heap[parent] > m_heap[child]) break;
swap(m_heap[parent], m_heap[child]);
parent = child;
child = 2 * parent + 1;
}
}
};
int main()
{
PriorithyQueue pq;
pq.push(100);
pq.push(300);
pq.push(200);
pq.push(500);
pq.push(400);
while (!pq.empty())
{
cout << pq.top() << endl;
pq.pop();
}
}