-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2021_HeapMin3.cpp
142 lines (128 loc) · 2.51 KB
/
2021_HeapMin3.cpp
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
//
// Created by dongwan-kim on 2022/05/05.
//
#include<iostream>
#include<vector>
using namespace std;
struct HeapMin{
int size;
vector<int> v;
HeapMin(){
v.push_back(-1);
size=0;
}
bool empty(){
if(size==0)
return true;
else
return false;
}
void Size(){
cout<<size<<endl;
}
void swap(int idx1, int idx2){
v[0]=v[idx1];
v[idx1]=v[idx2];
v[idx2]=v[0];
}
void upHeap(int idx){
if(empty())
cout<<-1<<endl;
else{
if(size==1)
return;
else{
int parent=idx/2;
if(v[parent]>v[idx]){
swap(parent,idx);
upHeap(parent);
}
}
}
}
void downHeap(int idx){
int left=idx*2;
int right=idx*2+1;
int child;
if(left>size)
return;
else if(left==size)
child=left;
else{
if(v[left]<v[right])
child=left;
else
child=right;
}
if(v[child]<v[idx]){
swap(child,idx);
downHeap(child);
}
}
void insert(int e){
v.push_back(e);
size++;
upHeap(size);
}
void min(){
if(empty())
cout<<-1<<endl;
else{
cout<<v[1]<<endl;
}
}
void removeMin(){
if(empty())
cout<<-1<<endl;
else{
int top=v[1];
v[1]=v[size];
size--;
v.pop_back();
downHeap(1);
cout<<top<<endl;
}
}
void print(){
if(empty())
cout<<-1<<endl;
else{
for(int i=1;i<=size;i++){
cout<<v[i]<<" ";
}
cout<<endl;
}
}
};
int main(){
int t;
cin>>t;
HeapMin hm;
while(t--){
string cmd;
cin>>cmd;
if(cmd=="insert"){
int a;
cin>>a;
hm.insert(a);
}
else if(cmd=="size"){
hm.Size();
}
else if(cmd=="empty"){
if(hm.empty())
cout<<1<<endl;
else
cout<<0<<endl;
}
else if(cmd=="min"){
hm.min();
}
else if(cmd=="removeMin"){
hm.removeMin();
}
else if(cmd=="print"){
hm.print();
}
}
}