-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMin Heap.cpp
159 lines (129 loc) · 2.71 KB
/
Min Heap.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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#include <bits/stdc++.h>
using namespace std;
typedef unsigned short usint;
typedef unsigned uint;
typedef long lint;
typedef short sint;
typedef long double ld;
typedef unsigned long ulint;
typedef unsigned long long ullint;
typedef long long llint;
#define INF ullint(2e9)
#define MOD 1000000007
#define mp make_pair
#define mt make_tuple
#define pii pair <int,int>
#define pib pair <int,bool>
#define pll pair <long,long>
#define pcc pair <char,char>
#define pui pair <uint,uint>
#define pul pair <ulint,ulint>
#define pff pair <float,float>
#define pllll pair <llint,llint>
#define pss pair <string,string>
#define pullull pair <ullint,ullint>
struct MinHeap
{
int *h;
int capacity;
int heap_size;
MinHeap(int cap)
{
heap_size = 0;
capacity = cap;
h = new int[cap];
}
int parent(int &i)
{
return (i-1)>>1;
}
int left(int &i)
{
return (i<<1)+1;
}
int right(int &i)
{
return (i<<1)+2;
}
void MinHeapify(int i)
{
int l = left(i);
int r = right(i);
int smallest = i;
if (l < heap_size && h[l] < h[i])
smallest = l;
if (r < heap_size && h[r] < h[smallest])
smallest = r;
if (smallest != i)
{
swap(h[i],h[smallest]);
MinHeapify(smallest);
}
}
void insertKey(int k)
{
if (heap_size == capacity)
{
cout << "Overflow!\n";
return;
}
++heap_size;
int i = heap_size-1;
h[i] = k;
while (i && h[parent(i)] > h[i])
{
swap(h[i],h[parent(i)]);
i = parent(i);
}
}
void decreaseKey(int i, int newVal)
{
h[i] = newVal;
while (i && h[parent(i)] > h[i])
{
swap(h[i],h[parent(i)]);
i = parent(i);
}
}
int getMin()
{
if (heap_size < 1) return INF;
return h[0];
}
int extractMin()
{
if (heap_size <= 0) return INF;
if (heap_size == 1)
{
--heap_size;
return h[0];
}
int root = h[0];
h[0] = h[heap_size-1];
--heap_size;
MinHeapify(0);
return root;
}
void deleteKey(int i)
{
decreaseKey(i,-INF);
extractMin();
}
};
int main()
{
ios_base::sync_with_stdio(0);
MinHeap mh(11);
mh.insertKey(3);
mh.insertKey(2);
mh.deleteKey(1);
mh.insertKey(15);
mh.insertKey(5);
mh.insertKey(4);
mh.insertKey(45);
cout << mh.extractMin() << ' ';
cout << mh.getMin() << ' ';
mh.decreaseKey(2,1);
cout << mh.getMin() << '\n';
return 0;
}