-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPQ.cpp
More file actions
99 lines (90 loc) · 2.05 KB
/
Copy pathPQ.cpp
File metadata and controls
99 lines (90 loc) · 2.05 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
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Node{
string task;
int priority;
Node(string t, int p){
task = t;
priority = p;
}
};
void upHeapify(vector<Node*>& heap,int index){
int parentIndex = (index - 1)/2;
Node* temp;
while(parentIndex >= 0 && heap[parentIndex]->priority < heap[index]->priority){
temp = heap[parentIndex];
heap[parentIndex] = heap[index];
heap[index] = temp;
index = parentIndex;
parentIndex = (index - 1)/2;
}
}
void downHeapify(vector<Node*>& heap){
int LChild;
int RChild;
int i = 0;
int size = heap.size();
int largest;
Node* temp;
while (true)
{
LChild = 2 * i + 1;
RChild = 2 * i + 2;
largest = i;
if (LChild < size && heap[LChild] > heap[largest])
{
largest = LChild;
}
if (RChild < size && heap[RChild] > heap[largest])
{
largest = RChild;
}
if (largest == i)
{
break;
}
temp = heap[i];
heap[i] = heap[largest];
heap[largest] = temp;
i = largest;
}
}
void Delete(vector<Node*>& heap){
Node* temp = heap[heap.size() - 1];
heap[heap.size() - 1] = heap[0];
heap[0] = temp;
delete heap[heap.size()-1];
heap.pop_back();
downHeapify(heap);
}
void displayHeap(vector<Node*>heap){
for (size_t i = 0; i < heap.size(); i++)
{
cout<<heap[i]->task<<": "<<heap[i]->priority<<endl;
}
}
int main(int argc, char const *argv[])
{
int priority;
string task;
vector<Node*> heap;
for (size_t i = 0; i < 10; i++)
{
cout<<"Enter the name of the task: ";
cin>>task;
cout<<"Enter the task's priority: ";
cin>>priority;
Node* node = new Node(task,priority);
heap.push_back(node);
if (i != 0)
{
upHeapify(heap,i);
}
cout<<endl;
}
Delete(heap);
displayHeap(heap);
return 0;
}