为啥过不了啊,www,求助
查看原帖
为啥过不了啊,www,求助
959579
xiaobu_dean楼主2023/10/28 16:48
// 堆的基本操作有
// 1.在堆中插入一个数x: h[++size] = x,up(size)
// 2.输出堆中的最小值:h[1]
// 3.删除堆中的最小值:h[1] = h[size],size--,down(1)

#include <bits/stdc++.h>
using namespace std;

using ll = long long ;
const int N = 1e6 + 50;
int h[N],len;
//--------down---------//
void down(int u) { // 下沉
	int t = u; // t表示结点i,与它的左儿子,右儿子之中的最小值
	if (2*u <= len&& h[2*u] < h[t]) t = 2*u; // 左儿子
	if (2*u+1 <= len && h[2*u+1] < h[t]) t = 2*u; // 右儿子
	if (t != u) {
		swap(h[t],h[u]);
		down(t); // 递归处理t
	}
}
//--------up---------//
void up(int u) { // 上浮
	// 比较当前点与其父亲结点的关系
	while (u / 2 && h[u] < h[u/2]) {
		swap(h[u],h[u/2]);
		u /= 2;
	}
}
int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
    int n; cin >> n;
    while (n--) {
    	int op; cin >> op;
    	int x;
    	if (op == 1) { // 插入x
    		cin >> x;
    		h[++len] = x;
    		up(len);
    	}
    	else if (op == 2) { // 输出最小值
    		cout << h[1] << '\n';
    	}
    	else if (op == 3) { // 删除最小值
    		h[1] = h[len];
    		len--;
    		down(1);
    	}
    }
	return 0;
}
2023/10/28 16:48
加载中...