0%

二叉堆

概念

二叉堆是一种特殊的堆,二叉堆是完全二元树(二叉树)或者是近似完全二元树(二叉树)。二叉堆有两种:最大堆和最小堆。最大堆:父结点的键值总是大于或等于任何一个子节点的键值;最小堆:父结点的键值总是小于或等于任何一个子节点的键值。

存储

二叉堆是一种数组对象,它可以被视为一棵完全二叉树。树中每个结点与数组中存放该结点中值的那个元素相对应

二叉堆存储示意图

put

操作

1.在堆尾加入一个元素,并把这个结点置为当前结点

2、比较当前结点和它父结点的大小
如果当前结点小于父结点,则交换它们的值,并把父结点置为当前结点,继续转2
如果当前结点大于等于父结点,则转3

3、结束

代码

1
2
3
4
5
6
7
8
9
10
11
12
void Put(int num) {
heap[++size] = num;
int x = size;
while (x > 1) {
if (heap[x] < heap[x >> 1]) {
swap(heap[x], heap[x >> 1]);
x >>= 1;
}
else break;
}
return;
}

get

操作

1、取出堆中根结点的值

2、把堆的最后一个结点(heap_size)放到根的位置上,把根覆盖掉, 堆长度减一

3、把根结点置为当前父结点,即当前操作结点now

4、如果now无儿子(now>heap_size/2),则转6;否则,把now的两(或一)个儿子中值较小的那一个置为当前子结点son

5、比较now与son的值,如果now的值小于等于son,转6;否则交换 两个结点的值,把now指向son,转4

6、结束

代码

1
2
3
4
5
6
7
8
9
10
11
12
void Get() {
heap[1] = heap[size--];
int x = 1;
while (x <= (size >> 1)) {
int son = x * 2;
if (son < size && heap[son + 1] < heap[son]) son++;
if (heap[x] <= heap[son]) break;
swap(heap[x], heap[son]);
x = son;
}
return;
}

例题

堆排序


n个数,我们利用堆把它们从小到大排序。


样例输入

1
2
8
2 3 9 4 5 3 6 7

样例输入

1
2
8
2 3 9 4 5 3 6 7

分析

利用小根堆的特性,最小值在根元素,每次取出根元素并删除,直到堆为空即可

AC代码

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
#include <cstdio>
#include <algorithm>

using namespace std;

const int MAXN = 1000005;

int n, heap[MAXN], size = 0;

void Put() {
int x = size;
while (x > 1) {
if (heap[x] < heap[x >> 1]) {
swap(heap[x], heap[x >> 1]);
x >>= 1;
}
else break;
}
return;
}

void Pop() {
heap[1] = heap[size--];
int x = 1;
while (x <= (size >> 1)) {
int son = x * 2;
if (son < size && heap[son + 1] < heap[son]) son++;
if (heap[x] <= heap[son]) break;
swap(heap[x], heap[son]);
x = son;
}
return;
}

int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &heap[++size]);
Put();
}
for (int i = 1; i <= n; i++) {
printf("%d ", heap[1]);
Pop();
}
return 0;
}

合并果子


luoguP1090


分析

用贪心来思考,每次肯定是取出最小的两堆进行合并,这里也利用了小根堆的特性,每次取出两个根元素,将它们的和累加在ans上,并作为一个新元素加入堆,
重复执行此操作n-1次,直到堆中只剩一个元素为止

AC代码

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
#include <cstdio>
#include <algorithm>

using namespace std;

const int MAXN = 10005;

int n, heap[MAXN], size = 0, ans = 0;

void Put() {
int x = size;
while (x > 1) {
if (heap[x] < heap[x >> 1]) {
swap(heap[x], heap[x >> 1]);
x >>= 1;
}
else break;
}
return;
}

void Pop() {
heap[1] = heap[size--];
int x = 1;
while (x <= (size >> 1)) {
int son = x * 2;
if (son < size && heap[son + 1] < heap[son]) son++;
if (heap[x] <= heap[son]) break;
swap(heap[x], heap[son]);
x = son;
}
return;
}

int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &heap[++size]);
Put();
}
for (int i = 1; i < n; i++) {
int a = heap[1];
Pop();
int b = heap[1];
Pop();
ans += a + b;
heap[++size] = a + b;
Put();
}
printf("%d", ans);
return 0;
}

欢迎关注我的其它发布渠道