跳到正文

个人记录

堆

smallycat约 3 分钟
原文

这是 2026年3月24日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年3月24日
收录
2026年3月24日
更新
2026年11月11日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

今天依旧总结好吧……

堆:

一个看起来有点弱智的东西,没啥好介绍的。
就说说函数吧:

q.push(x)

复杂度:O(logn)O(log_n)

C++
void push(int x){
	heap[++len] = x;
	int i = len;
	while(i > 1 && heap[i] < heap[i / 2]){
		swap(heap[i], heap[i / 2]);
		i /= 2; 
	}
}

q.pop()

复杂度:O(logn)O(log_n)

C++
void pop(){
	heap[1] = heap[len--];
	int i = 1;
	while(2 * i <= len){
		int son = 2 * i;
		if(son + 1 <= len && heap[son] > heap[son + 1]){
			son++;
		}
		if(heap[son] < heap[i]){
			swap(heap[son], heap[i]);
			i = son;
		}
		else break;
	}
}

q.top()

复杂度:O(1)O(1)

C++
int top(){
    return heap[1];
}

好吧复习了这么多 好麻烦啊 要不不学了? 等等 其实它有自带函数的 哈哈哈


自带函数其实就是刚刚的大标题
等等等 不会吧 多久没刷题
自己上课辛辛苦苦整出来的函数都忘了!!!
别学了 摆烂吧 oi刷题第一 一直刷题你怎么可能会忘 啊?
如果全忘了的话 小木老师的课不是白上了吗 你在干什么啊!
跟你说啊 你应该没忘了你上课写了半天结果想起来有函数的绝望吧 hhhhh 再嘲笑一次你 hhhhh

自带函数:

以P3378为例
跟你说老简单了 但是,先看看小根堆怎么定义吧!
笨死了 学过的都忘了
你也是被鉴定为知识界最好的守门员了(小木是球员 小根堆是球)

C++
priority_queue<int,vector<int>,greater<int> > q1; //小根堆(优先队列 其实画出来是完全二叉树
priority_queue<int,vector<int>,less<int> > q2;//大根堆

正式代码:

C++
while (n--) {
    int op, x;
    cin >> op;

    if (op == 1) {
        cin >> x;
        q.push(x);
    } else {
        if (op == 3) {
            q.pop();
        } else {
            if (op == 2) {
                cout << q.top() << endl;
            }
        }
    }
}