6. 堆与优先队列
习题
#30008
⚡4⏳4
实现不透明的整数小根堆:
c
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
typedef struct IntMinHeap IntMinHeap;
IntMinHeap *int_min_heap_create(void);
void int_min_heap_destroy(IntMinHeap *heap);
bool int_min_heap_push(IntMinHeap *heap, int64_t value);
bool int_min_heap_peek(
const IntMinHeap *heap,
int64_t *out_value
);
bool int_min_heap_pop(
IntMinHeap *heap,
int64_t *out_value
);
size_t int_min_heap_size(const IntMinHeap *heap);1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
要求:
- 数组表示必须保持小根堆不变式;重复值按普通元素处理。
- 堆拥有自己的存储;扩容失败或容量计算溢出时
push返回false,堆保持不变。 - 空堆或参数无效时
peek、pop返回false,不得修改输出对象。 destroy(NULL)安全,size(NULL)返回 0。push和pop的时间复杂度为 ,peek为 。
#30009
⚡4⏳3
实现从整数数组中选出最小的前 k 个元素:
c
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
bool smallest_k_i64(
const int64_t *items,
size_t count,
size_t k,
int64_t *out_items
);1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
要求:
out_items必须按非递减顺序保存结果;相等值可以来自任意对应位置。k == 0时操作成功,此时两个数组都可以为空;k > count时返回false。- 输入数组不得修改;参数无效、分配失败或大小计算溢出时,输出数组保持不变。
- 使用大小为
k的堆,将时间复杂度控制在 ,额外空间复杂度为 。
#30010
⚡5⏳4
合并多条已经按非递减顺序排列的整数序列:
c
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
bool merge_sorted_i64(
const int64_t *const *sequences,
const size_t *counts,
size_t sequence_count,
int64_t *out_items,
size_t capacity,
size_t *out_count
);1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
要求:
out_items按所有输入序列的整体非递减顺序保存结果,并保持每条序列内部的先后顺序。sequence_count == 0时结果长度为 0;非空序列的指针必须有效,空序列指针可以为NULL。- 总长度计算溢出、容量不足或参数无效时返回
false,不得修改输出数组和*out_count。 - 使用最小堆维护每条序列的当前首元素,时间复杂度为
,其中 为总元素数、 为序列数。