← 返回首页
学习思考

c++中堆的实现

在上周的一场周赛中,要用到堆,但是我并不知道如何初始化堆,虽然并没有很影响通过速度,但还是从大佬的代码中学到了很多:

普通堆的实现:

堆其实就是完全二叉树的线性存储形式

839. 模拟堆

c++
#include<bits/stdc++.h> using namespace std; const int N = 100010; int h[N], ph[N], hp[N], cnt; int n, idx = 0, x, c; string op; void heap_swap(int a, int b) { swap(ph[hp[a]], ph[hp[b]]); swap(hp[a], hp[b]); swap(h[a], h[b]); } void down(int u) { int t = u; if(u * 2 <= cnt && h[u * 2] < h[t]) t = u * 2; if(u * 2 + 1 <= cnt && h[u * 2 + 1] < h[t]) t = u * 2 + 1; if(u != t) { heap_swap(u, t); down(t); } } void up(int u) { while(u / 2 && h[u] < h[u / 2]) { heap_swap(u, u / 2); u >>= 1; } } int main() { cin >> n; while(n--) { cin >> op; if(op == "I") { scanf("%d", &x); cnt++; idx++; ph[idx] = cnt, hp[cnt] = idx; h[cnt] = x; up(cnt); } else if(op == "D") { scanf("%d", &x); x = ph[x]; heap_swap(x, cnt); cnt --; up(x); down(x); } else if(op == "C") { scanf("%d %d", &x, &c); x = ph[x]; h[x] = c; up(x); down(x); } else if(op == "DM") { heap_swap(1, cnt); cnt--; down(1); } else { printf("%d\n", h[1]); } } return 0; }

以上并不是本篇文章重点,代码下去自己背去,下边才是重点

优先队列:

声明:

c++
priority_queue<int> q; // 大根堆 priority_queue<int, vector<int>, greater<int>> q; // 小根堆 priority_queue<pair<int, int>>q;

操作:

💡
push // 把元素插入堆 pop // 删除堆顶元素 top // 查询堆顶元素(最大值)

堆的函数:

C++的STL提供了make_heap、push_heap、pop_heap、sort_heap等算法,它们用来将一个随机存储的数组或者容器等转换为一个heap。

这里所说的转换为heap意思是将原来的存储顺序改变,将转换成的堆层序遍历后所得到的元素顺序作为数组或者容器新的元素顺序(实质上就是对原来的数据用一个算法换了一下元素顺序)。

1、make_heap

函数声明:

c++
template <class RandomAccessIterator> void make_heap(RandomAccessIterator first, RandomAccessIterator last); template <class RandomAccessIterator, class Compare> void make_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp);

2、push_heap

函数声明:

c++
template <class RandomAccessIterator> void push_heap(RandomAccessIterator first, RandomAccessIterator last); template <class RandomAccessIterator, class Compare> void push_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp);

3、pop_heap

函数声明:

c++
template <class RandomAccessIterator> void pop_heap(RandomAccessIterator first, RandomAccessIterator last); template <class RandomAccessIterator, class Compare> void pop_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp);

4、sort_heap

函数声明:

c++
template <class RandomAccessIterator> void sort_heap(RandomAccessIterator first, RandomAccessIterator last); template <class RandomAccessIterator, class Compare> void sort_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp);

本文由 GJJ 创作,内容来源于 Notion 数据库,随时可在 Notion 中编辑更新。 本站由 DeepSeek-v4-flash 辅助构建,项目参考 NotionNext

← 返回首页
61
文章
6
标签
3
分类
962
运行天数