小根堆求助
  • 板块学术版
  • 楼主tder
  • 当前回复0
  • 已保存回复0
  • 发布时间2023/12/16 13:52
  • 上次更新2023/12/16 14:28:32
查看原帖
小根堆求助
714254
tder楼主2023/12/16 13:52
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e6 + 5;
int n;
class heap {
	private:
		int a[N], t = 0;
	public:
		int size() {
			return t;
		}
		int empty() {
			return !size();
		}
		int push(int k) {
			a[++t] = k;
			int c = t;
			while(a[c] < a[c / 2] && c > 1) {
				swap(a[c], a[c / 2]);
				c /= 2;
			}
			return c;
		}
		int top() {
			assert(size());
			return a[1];
		}
		void pop() {
			assert(size());
			a[1] = a[t];
			a[t--] = 0;
			int c = 1;
			while(a[c] > min(a[c * 2], a[c * 2 + 1]) && c * 2 <= t) {
				if(a[c * 2] < a[c * 2 + 1]) {
					swap(a[c], a[c * 2]);
					c *= 2;
				} else {
					swap(a[c], a[c * 2 + 1]);
					c *= 2, c += 1;
				}
			}
		}
} s;
signed main() {
	cin>>n;
	for(int i = 1; i <= n; i++) {
		int op, x;
		cin>>op;
		if(op == 1) {
			cin>>x;
			s.push(x);
		} else if(op == 2) {
			cout<<s.top()<<endl;
		} else {
			s.pop();
		}
	}
	return 0;
}
2023/12/16 13:52
加载中...