P3378 【模板】堆

大根堆

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
#include<bits/stdc++.h>
using namespace std;
const int MAXn = 1000000;

inline int read() {
register char c;
for (c = getchar(); (c < '0' || c>'9') && c != '-'; c = getchar());
register bool f = c == '-';
register int s = f ? 0 : c - '0';
for (c = getchar(); c >= '0' && c <= '9'; c = getchar()) {
s = (s << 3) + (s << 1) + c - '0';
}
return f ? -s : s;
}

int heap[MAXn + 10];
int heapn;
int n;
void Up(int p) {
int f = p / 2;
while (p > 1) {
if (heap[p] < heap[f]) {
swap(heap[p], heap[f]);
p = f;
f /= 2;
} else break;
}
}
void Down(int p) {
int s = p * 2;
while (s <= heapn) {
if (heap[s] > heap[s + 1] && s < heapn) {
s++;
}
if (heap[s] < heap[p]) {
swap(heap[s], heap[p]);
p = s;
s *= 2;
} else break;
}
}
void Insert(int x) {
heap[++heapn] = x;
Up(heapn);
}
void Pop(int p) {
heap[p] = heap[heapn--];
Up(p);
Down(p);
}
void PopRoot() {
heap[1] = heap[heapn--];
Down(1);
}
int GetRoot() {
return heap[1];
}

int main() {
int opt;
n = read();
while (n--) {
opt = read();
switch (opt) {
case 1:
Insert(read());
break;
case 2:
printf("%d\n", GetRoot());
break;
case 3:
PopRoot();
break;
}
}
}

小根堆

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
#include<bits/stdc++.h>
using namespace std;
const int MAXn = 1000000;

inline int read() {
register char c;
for (c = getchar(); (c < '0' || c>'9') && c != '-'; c = getchar());
register bool f = c == '-';
register int s = f ? 0 : c - '0';
for (c = getchar(); c >= '0' && c <= '9'; c = getchar()) {
s = (s << 3) + (s << 1) + c - '0';
}
return f ? -s : s;
}

int heap[MAXn + 10];
int heapn;
int n;
void Up(int p) {
int f = p / 2;
while (p > 1) {
if (heap[p] > heap[f]) {
swap(heap[p], heap[f]);
p = f;
f /= 2;
} else break;
}
}
void Down(int p) {
int s = p * 2;
while (s <= heapn) {
if (heap[s] < heap[s + 1] && s < heapn) {
s++;
}
if (heap[s] > heap[p]) {
swap(heap[s], heap[p]);
p = s;
s *= 2;
} else break;
}
}
void Insert(int x) {
heap[++heapn] = x;
Up(heapn);
}
void Pop(int p) {
heap[p] = heap[heapn--];
Up(p);
Down(p);
}
void PopRoot() {
heap[1] = heap[heapn--];
Down(1);
}
int GetRoot() {
return heap[1];
}

int main() {
Insert(1);
Insert(3);
Insert(1);
Insert(7);
Insert(11);
Insert(25);
cout << GetRoot() << endl;
PopRoot();
cout << GetRoot() << endl;
}