-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy path1prqueue.cpp
More file actions
100 lines (80 loc) · 2.07 KB
/
1prqueue.cpp
File metadata and controls
100 lines (80 loc) · 2.07 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
#include<bits/stdc++.h>
using namespace std;
class priorityqueue{
public:
vector<int>pq;
bool isempty(){
return pq.size()==0;
}
int getmin(){
if(isempty()){
return 0;
}
return pq[0];
}
int getsize(){
return pq.size();
}
void insert(int x){
pq.push_back(x);
int child_index=pq.size()-1;
while(child_index>0){
int parent_index=(child_index-1)/2;
if(pq[child_index]<pq[parent_index]){
int temp=pq[child_index];
pq[child_index]=pq[parent_index];
pq[parent_index]=temp;
}
else{
break;
}
child_index=parent_index;
}
}
int removemin(){
if(isempty()){
return 0;
}
int ans=pq[0];
pq[0]=pq[pq.size()-1];
pq.pop_back();
//downheapify
int parent_index=0;
int leftchild_index=2*parent_index+1;
int rightchild_index=2*parent_index+2;
while(leftchild_index<pq.size()){
int min_index=parent_index;
if(pq[min_index]>pq[leftchild_index]){
min_index=leftchild_index;
}
if(rightchild_index<pq.size() && pq[rightchild_index]<pq[min_index]){
min_index=rightchild_index;
}
int temp=pq[min_index];
pq[min_index]=pq[parent_index];
pq[parent_index]=temp;
parent_index=min_index;
int leftchild_index=2*parent_index+1;
int rightchild_index=2*parent_index+2;
if(min_index==parent_index){
break;
}
}
return ans;
}
};
int main(){
priorityqueue p;
p.insert(100);
p.insert(10);
p.insert(15);
p.insert(4);
p.insert(17);
p.insert(21);
p.insert(67);
cout<<p.getsize()<<endl;
while(!p.isempty()){
cout<<p.removemin()<<" ";
}
cout<<endl;
}